I have a function foo
that can get nil values under certain circumstances, i.e. foo(VarA)
while VarA
is undefined. This undefined VarA
should get interpreted as "VarA"
but I can't invoke foo("VarA")
because VarA
should act as an option param (different from normal string params).
mt = {__index = function(t, k) return k end}
setmetatable(_G, mt)
This would get the desired result but now every other undefined variable would return its name. Like abc -> "abc"
. Do you see any way to only have a metatable active in this specific case? I could switch metatables in my foo
method but when I'm in the foo
block, the passed param is already nil and its too late.
Appendix: I think the question was not specific enough. Schollii's answer to pass params as a table was good but does not work as intended:
foo({option1 = delete, option2 = push})
This should have the key information (option1 and option2) plus the information of the value (even though delete and push do not exist in global or local namespace). Schollii's approach would give me the key information but not the value information (like "delete" and "push"). I can't define delete and push beforehand because these new "key-words" should get defined by the function itself later on. Passing those new keywords as a string is no option.
local varA = varA or 'varA'
– hjpotter92foo(VarA)
with correspondingfoo("VarA")
and insert this line at the beginning of function foo(var):var = _G[var] or var
– Egor Skriptunoff