Why does only one of these work?

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)]
2 Likes

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)]
  • The table {1, 2} is stored in the variable a, making it persistent.
  • When you index 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.
  • Lua doesn’t store it anywhere, and depending on optimizations, it might get discarded before indexing happens.
1 Like

why does it work if you put the table in parentheses?

local n = ({1, 2})[math.random(1,2)]