Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a Lua table member exists at any level

Tags:

lua

lua-table

I need to check if a member exists in a table that isn't at the next level, but along a path of members.

foo = {}
if foo.bar.joe then
  print(foo.bar.joe)
end

this will cast an attempt to index field 'bar' (a nil value) because bar isn't defined.

My usual solution is to test the chain, piece-by-piece.

foo = {}
if foo.bar and foo.bar.joe then
  print(foo.bar.joe)
end

but this can be very tedious when there are many nested tables. Are there a better way to do this test than piece-by-piece?

like image 931
Max Kielland Avatar asked Jan 09 '23 05:01

Max Kielland


2 Answers

I don't understand what you try to mean by "along a path of members". From the example, I assume you are trying to find a value in a "subtable"?

local function search(master, target) --target is a string
    for k,v in next, master do
        if type(v)=="table" and v[target] then return true end
    end
end

A simple example. If you use such a function, you can pass the foo table and the joe string to see if foo.*.joe exists. Hope this helps.

like image 79
lyravega Avatar answered Feb 01 '23 10:02

lyravega


debug.setmetatable(nil, {__index = {}})

foo = {}
print(foo.bar.baz.quux)
print(({}).prd.krt.skrz.drn.zprv.zhlt.hrst.zrn)  -- sorry ))
like image 23
Egor Skriptunoff Avatar answered Feb 01 '23 12:02

Egor Skriptunoff