3 posts
Posted 01 May 2014 - 02: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?
62 posts
Posted 01 May 2014 - 05:43 AM
Define tInput as {} somewhere and make this line:
'tInput[2](tInput[1])'
into this:
'getfenv()[tInput[2]](tInput[1])'
8543 posts
Posted 01 May 2014 - 05: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.
62 posts
Posted 01 May 2014 - 06:07 AM
Yeah local variables are faster, but the environment is an actual table as well.
Edited on 01 May 2014 - 04:08 AM
8543 posts
Posted 01 May 2014 - 06: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.
62 posts
Posted 01 May 2014 - 06:30 AM
I just got confused because you said actual table. But yeah good point
8543 posts
Posted 01 May 2014 - 08:01 AM
Yeah, that was poor phrasing, I should have said "explicitly declared table" instead.