Search code examples
lualua-table

How can I define a sparse array in one statement in lua


As an example, I am doing this

local Bool = {} 
Bool [false]='OFF' 
Bool [true]='ON'

I thought this would work, but it doesn't

local Bool = {false='OFF', true='ON'}

How can I define it in one statement?


Solution

  • The notation you are trying to use only works when the indices can be written as identifiers, so alphanumeric + underscore, for any other values, numbers, weird strings, booleans, tables or functions, you want to use

    myTable = {[false] = "some value", [-1/12] = 0}
    

    You need to enclose indices in square brackets.

    Btw that's not a multidimensional array