Hi, I was just wondering if there was a simple explanation to why only one of these statements work.
-- This works...
local a = {1, 2}
local n = a[math.random(1,2)]
-- But this doesn't?
local n = {1, 2}[math.random(1,2)]
Hi, I was just wondering if there was a simple explanation to why only one of these statements work.
-- This works...
local a = {1, 2}
local n = a[math.random(1,2)]
-- But this doesn't?
local n = {1, 2}[math.random(1,2)]
This happens because of how Lua (and Luau) handles table expressions.
In your first example:
local a = {1, 2}
local n = a[math.random(1,2)]
{1, 2}
is stored in the variable a
, making it persistent.a[math.random(1,2)]
, Lua properly retrieves a value from the existing table.However, in your second example:
local n = {1, 2}[math.random(1,2)]
{1, 2}
is a temporary (anonymous) table, meaning it exists only for that moment.why does it work if you put the table in parentheses?
local n = ({1, 2})[math.random(1,2)]