Goles
Goles

Reputation: 11799

Correct way to access Multi-Dimensional Array with string indexes in Lua?

I'm trying to have a good access to multi-dimensional arrays with string indexes in Lua, here's basically what I'm trying to do:

rules =
{
    {"S_RIGHT", "A_STOP", "S_RESULT"},
}

matrix = {}

for _,v in pairs(rules) do

    if( matrix[ v[1] ] == nil ) then
        matrix[ v[1] ] = {}
    end

    matrix[ v[1] ][ v[2] ] = v[3]
end

-- results in error ( attempt to index field 'S_NO' a nil value)
var = matrix["S_NO"]["S_RESULT"] 

assert(var == nil, "Var should be nil")

A way to do it but quite verbose is:

var = matrix["S_NO"]

if var ~= nil then
    var = var["S_RESULT"] 
end

assert(var == nil, "Var should be nil")

Is there a way to make the first case to work ? ( less verbose )

Upvotes: 1

Views: 1037

Answers (1)

Goles
Goles

Reputation: 11799

Ok,

Found the answer.

If matrix is going to be read-only a correct approach would be:

local empty = {}
setmetatable(matrix, {__index=function() return empty end})

If I would like to allow writes and it's specifically two levels of tables, I could do:

setmetatable(matrix, {__index=function(t,k) local new={} rawset(t,k,new) return new end}

Hope this helps!

Upvotes: 2

Related Questions