1

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 )

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.