What is the difference in Lua between:
table[1] = var
table = { var }
Why the second option is safer? What will happen if table or var will be nil for both cases? Thanks!
Don't name your table table. table is Lua's table libray.
table[1] = var will acutally not create a new table. it will assign var to field 1 in the table library's table.
You need to create a table befor you can insert fields.
local t = {var} creates a new table that contains a single element var. If var is nil the table is empty.
local t = {}
t[1] = var
Does the same but in two steps. None of them is "safer". The first is just shorter and you don't have to care about numbering elements manually.
In some cases you cannot initialize fields in the table constructor {} if you want to refer to that table.
For me the best constructor for a table is simply: setmetatable()
It returns the first and set the second argument as metatable.
Examples for playing around with in console...
# /usr/local/bin/lua -i
Lua 5.4.3 Copyright (C) 1994-2021 Lua.org, PUC-Rio
> -- Empty table
> my_table=setmetatable({},empty)
> my_table
table: 0x56677820
> -- Empty table with __name
> my_table=setmetatable({},{__name='my_table'})
> my_table
my_table: 0x56677850
> -- Empty table with __name and __index table metamethods
> my_table=setmetatable({},{__name='my_table',__index=table})
> my_table:insert(math.pi)
> my_table:concat()
3.1415926535898
And my favorite destructor: my_table=empty
To destroy only a metatable from existing table use:
my_table=setmetatable(my_table,empty)