Sometimes Lua doesn't behave the way one would think after reading the documentation. Some of these cases are:
As expected, table.insert(my_table, 20)
adds the value 20
to the table, and table.insert(my_table, 5, 20)
adds the value 20 at the 5th position.
What does table.insert(my_table, 5, nil)
do though? One might expect it to treat nil
as no argument at all, and insert the value 5
at the end of the table, but it actually adds the value nil
at the 5th position of the table.
When is this a problem?
(function(tab, value, position)
table.insert(tab, position or value, position and value)
end)({}, 20)
-- This ends up calling table.insert({}, 20, nil)
-- and this doesn't do what it should (insert 20 at the end)
A similar thing happens with tostring()
:
print (tostring(nil)) -- this prints "nil"
table.insert({}, 20) -- this returns nothing
-- (not nil, but actually nothing (yes, I know, in lua those two SHOULD
-- be the same thing, but they aren't))
-- wrong:
print (tostring( table.insert({}, 20) ))
-- throws error because nothing ~= nil
--right:
local _tmp = table.insert({}, 20) -- after this _tmp contains nil
print(tostring(_tmp)) -- prints "nil" because suddenly nothing == nil
This may also lead to errors when using third party code. If, for example, the documentation of some function states "returns donuts if lucky, nil otherwise", the implementation might looks somewhat like this
function func(lucky)
if lucky then
return "donuts"
end
end
this implementation might seem reasonable at first; it returns donuts when it has to, and when you type result = func(false)
result will contain the value nil
.
However, if one were to write print(tostring(func(false)))
lua would throw an error that looks somewhat like this one stdin:1: bad argument #1 to 'tostring' (value expected)
Why is that? tostring
clearly gets an argument, even though it's nil
. Wrong. func returns nothing at all, so tostring(func(false))
is the same as tostring()
and NOT the same as tostring(nil)
.
Errors saying "value expected" are a strong indication that this might be the source of the problem.
This is a huge pitfall if you're new to lua, and there's a lot of information in the tables category