Help Support the Baja Engine! Donate to Breezeway Studios!
Lua Pitfalls

Search:

Lua is Pass-By-Reference for tables!


Lua is pass-by-value for strings,numbers, etc, but is pass-by-reference for tables! This can be confusing!

Code

-- pass-by-value
u=5
print(u) --prints '5'
function test(x) x=8 end
print(u) --prints '5'

--BUT: tables are pass-by-reference
u={}
u.a=1
u.b=1
print(u.a) -- prints '1'
function test(x) x.a=2; x.b=2; end
test(u)
print(u.a) -- prints '2', not '1'!


Note: this also applies to returning tables from functions! In this case, each time you return the table from the function, it will allocate new memory to store the table, and will not automatically destroy it - it will be destroyed later by the garbage collector. This is not necessarily a bad thing, but if the function is frequently called this can cause the engine to spend a lot of time collecting garbage. If possible, return the values separately, instead of in a table, to prevent the memory allocation.

Code

function getpos()
        return {x=2,y=3}
end

function getposnomem()
        return x,y
end


Copying Tables


Because tables are actually references (see above), when you copy a table to another variable, changes in the first table are reflected in the copy.

Limits of number variables


Lua variables are stored in memory as doubles, but many of the engine variables are stored in memory as floats. Because of this, it isn't always safe to directly compare a lua variable and a variable in the engine libraries. For example, a number in lua such as 2.123168743218613 set as camera.rot.y could actually make camera.rot.y 2.123168743217321. So, if you try to compare these values later like:

Code

if camera.rot.y == x then run() end


it will come up false even though it should be true.

As a workaround, used math.round() on both of the numbers. Or, test with inequalities (>,<) instead of .

In reality, numbers are usually not precise enough for it to matter, but this can crop up on rare occasions and lead to almost impossible to find bugs.