lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

> I would like to check if a function exist. But the name of the function
> is stored in a string like this: "Here.And.There" Or alternative in a
> table like this Table={'Here','And','There'} or in any other form.

Here's a suggestion (Lua 5, but Lua 4 is similar):

-- string form
local function locate(table, path)
    local t = table
    string.gsub(path, "(%w+)", function(part)
        t = t and t[part]
    end)
    return t
end

-- table form
local function locate2(table, parts)
    local t = table
    for _, v in ipairs(parts) do
        t = t[v]
        if not t then break end
    end
    return t
end

local function f()
    print "aap"
end

table = {
    Here = {
        And = {
            There = f
        }
    }
}

locate(table, "Here.And.There")()  -- prints "aap"
print(locate(table, "Here.Or.There"))  -- prints nil

locate2(table, {'Here', 'And', 'There'})()   -- prints "aap"
print(locate2(table, {'Here', 'Or', 'There'}))  -- prints nil

-- try something fancy...

setmetatable(table, {
    __call = function(table, parts)
        return locate2(table, parts)
    end
})

table {'Here', 'And', 'There'} ()  -- prints "aap"

Bye,
Wim