1

Been having fun with a homebrew doco system in Lua. e.g.

fun("abs","return abs value", function (x,y)
        return math.abs(x,y) end)

I'm stuck on one detail. I want to make "abs" a local function . But I do not know how to do that programmatically.

Of course, I could write to a field in some Lib object and call it Lib.abs(x,y) and I think that is what I'm going to have to do. BUT can any smart Lua person tell me how to not do that?

2 Answers 2

2

I don't think you have much of a choice, as while you can assign a value to a local variable (using debug.setlocal function), it's assigned by index, not by name, so there has to exist a local variable already with that index.

I don't see anything wrong with your suggestion to store the function in a table field.

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

Comments

0

What I would do is, I'd write(or even override) _G, run your function/program, and then restore it.

function callSandboxed(newGlobals, func)
    local oldGlobals = {} --make a new table to store the values to be writen (to make sure we don't lose any values)
    for i,_ in pairs(newGlobals) do
        table.insert(oldGlobals, _G[i]) --Store the old values
        _G[i] = newGlobals[i] --Write the new ones
    end
    func() --Call your function/program with the new globals
    for i,v in pairs(oldGlobals) do
        _G[i] = v --Restore everything
    end
end

In this case, what you want to do is:

--Paste the callSandboxed function

callSandboxed({abs=math.abs},function()print(abs(-1))end) --Prints 1

If you want to remove ALL the old values from _G (not only the ones you want to replace), then you could use this:

function betterCallSandboxed(newGlobals, func) --There's no point deep copying now, we will replace the whole table
    local oldGlobals = _G --Make a new table to store the values to be writen (to make sure we don't lose any values)
    _G = newGlobals --Replace it with the new one
    func() --Call your function/program with the new globals
    _G = oldGlobals
end

Now if inside func, print and math(etc) are nil.

2 Comments

rewrite _G? (or in Lua 5+, rewrite _ENV)? interesting approach. does _G=_ENV={abs=math.abs} mean that everything else in the global environment is now in accessible?
Oh, thanks for telling me about _ENV. I'm used to working with old versions of lua, so I haden't realised this new _ENV thing. I think I'll stick to _G, though, for compatibility

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.