Difference between revisions of "Lua for TIC80"

Like most (imperative) programming languages lua is based on variables, if-then and loop structures, and functions.

Assignment

Remember, unlike what you learned in your algebra class, the single equals sign in an assignment isn't about expressing a long term equality relationship. It's a transactional active structure that does two key things:

1. evaluate / calculate the right hand side (RHS), then...
2. store the computed value to a named reference (either a simple variable, or reference inside a table).

Once it's done the code continue and the same variable can be re-assigned to a new value, as in the frequent used case of incrementing a variable.

a = "hello" .. "world"
x = x + 1
t.n = tostring(x)

tables

Tables are the main data structure in Lua.

See:

Tables can be used to store a list of values. The # operator returns the last index (usually, see note below).

squares={1,4,9,16,25,36,49,64,81}

function TIC()
cls(0)
for i=1,#squares do
print(i,i*16,0)
print(squares[i],i*16,10)
end
end

Lua tables can also be like python dictionaries (and javascript objects)...

PLANE={
START_FUEL=2000,
MAX_FUEL=4000,
FUEL_INC=1000,
FUEL_BAR_W=50
}

Tables can be *nested* (one inside the other)...

LVL={
{
name="1-1",bg=2,
palor={},
pkstart=8,pklen=3,
mus=BGM.A,
},
{
name="1-2",bg=0,
palor={=0x102428},
pkstart=11,pklen=2,
mus=BGM.B,
}
}

Examples from: 8-bit panda

More useful examples:

{x=0, y=0}

is equivalent to

{["x"]=0, ["y"]=0}

and the constructor

{"red", "green", "blue"}

is equivalent to

{="red", ="green", ="blue"}

For those that really want their arrays starting at 0, it is not difficult to write the following:

days = {="Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}

if

if btn(0) then
t=t+1
elseif btn(1) then
t=t-1
end for

function TIC()
cls(0)

for i=1,100,2 do
rect(0,0,i,i,i%16)
end

end