Hugo Schmitt
Hugo Schmitt

Reputation:

Import functions from table as local functions in Lua

I want to achieve this (import functions from util table as local values):

function blah () 
 local x = util.x
 local y = util.y
 ...
end

without having to reference each function explicitly, e.g. something like:

function blah()
  for name,f in util do 
    ???
  end
end

Unfortunately there is no local table that I could set the way one can set _G['function_name_as_string']. Ideas?

Upvotes: 4

Views: 757

Answers (2)

RBerteig
RBerteig

Reputation: 43326

IIRC, I have seen an example for metalua that enables something like this. It operates on the abstract syntax tree and as a result can introduce new keywords and syntax into the language.

Upvotes: 2

August Lilleaas
August Lilleaas

Reputation: 54593

As far as I know, you can't set local variables by name. You'd have to do it explicitly.

Fyi, the reason for there not being a _L table similar to _G is because of the lexical scoping. It is possible to have the same local variable names in multiple scopes, yet they aren't the same variables. You would have to have a setlocal("foo", xxx) kind of thing, but Lua doesn't have that.

Upvotes: 4

Related Questions