Jump to content




Getting a table to run as a function


  • You cannot reply to this topic
6 replies to this topic

#1 Xiges

  • Members
  • 3 posts

Posted 01 May 2014 - 01:33 AM

function on(type)
  >insert code here
end


while true do
print("Check farms' Statuses or toggle them On and Off")
print("Press any key to input")
local e, i, msg = os.pullEvent()
if e == "char" then
  print("Oak, Rubber, Animals, Cactus?")
  local tInput[1] = tonumber(read())
  print("Status, On, Off?")
  local tInput[2] = tonumber(read())
  tInput[2](tInput[1])
end
end

trying to have it on rednet while not in use, and if someone hits a key it will take 2 inputs. These will then run as a function and its parameter

Also, how would I make it so that there is a 10 second window for all the input to happen, and if it does not happen within this time it will just go back to the initial while loop?

#2 HometownPotato

  • Members
  • 62 posts

Posted 01 May 2014 - 04:43 AM

Define tInput as {} somewhere and make this line:
'tInput[2](tInput[1])'
into this:
'getfenv()[tInput[2]](tInput[1])'

#3 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 01 May 2014 - 04:56 AM

Yuck. Just because something would technically work, doesn't make it a good solution. A better solution would be to put the functions in an actual table and index that:

local actions = {
  on = function(arg)
	--# do stuff
  end,
  off = function(arg)
	--# do different stuff
  end,
}

local material = read()
local action = read()

actions[action](material)

It's best to try to localize everything wherever possible.

#4 HometownPotato

  • Members
  • 62 posts

Posted 01 May 2014 - 05:07 AM

Yeah local variables are faster, but the environment is an actual table as well.

Edited by HometownPotato, 01 May 2014 - 05:08 AM.


#5 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 01 May 2014 - 05:19 AM

Indeed, but using globals and getfenv is hacky and not in line with best practices. It also works, it's just not a good way of doing it, unless absolutely necessary, which is not the case here. In Ask a Pro, we often end up teaching people how to do things with Lua, as this is many people's first exposure to the language. It's better to show someone the right way of doing something, even if it involves more than just one changed line of code.

#6 HometownPotato

  • Members
  • 62 posts

Posted 01 May 2014 - 05:30 AM

I just got confused because you said actual table. But yeah good point

#7 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 01 May 2014 - 07:01 AM

Yeah, that was poor phrasing, I should have said "explicitly declared table" instead.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users