This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
corisco1917's profile picture

[LUA]API declaring functions dinamically

Started by corisco1917, 05 February 2013 - 04:06 AM
corisco1917 #1
Posted 05 February 2013 - 05:06 AM
i am trying to declare function dinamicaly in a api file…

so a have a variable
local collection = { x = " ", y = " ", z = " " }

which i iterate inside my api and inside the for in pairs(collection) and declare some global functions…

outside for in i have a private function named save which all colection will be receiving this functions
local function save () –do something end

so for my loop looks like this



local collection = { turtle = "", computer = "", chest = "", }

local function save ()
  print(computer_path)
end

for key,value in pairs(collection) do
	key = { save = save, }
end

but i can't use self inside api to declare the variables globally inside the for in loop… does anyone have a workaround for this?

outside the api file i want to access those dinamically declared function like filename.x.save() filname.y.save() etc..
GopherAtl #2
Posted 05 February 2013 - 05:38 AM
getfenv() with no parameters returns the function environment currently being executed in. In an api, you can do this:



local myFEnv=getfenv()

myFEnv["dynamicMember"] = "some value"

Then you will be able to access it after calling os.loadAPI("myapi") as myapi.dynamicMember
corisco1917 #3
Posted 05 February 2013 - 05:41 AM
very good gopher that worked just fine, thanks!!!