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

Having problem running a array function

Started by aceyo369, 15 August 2014 - 04:21 PM
aceyo369 #1
Posted 15 August 2014 - 06:21 PM
I wanted to store a function in an array called menu here, and the function is called handler, so i don't know why when i call <menu[select].handler()> called out Nil… Maybe i used it wrongly, i need enlightenment for this error.

This is the code:

local w,h = term.getSize()

local select = 1

local function clear()
term.clear()
term.setCursorPos(1,1)
end

local function printCentered(word, h)
term.setCursorPos(w/2 - #word/2, h)
term.write(word)
end

local function runApp()

end

local function editApp()

end

local function seeApp()

end

local menu = {
[1] = {text = "Run a program", handler = runApp()},
[2] = {text = "Make or edit a program", handler = editApp()},
[3] = {text = "See existing program", handler = seeApp()}
}

local function printMenu()
clear()
for i = 1, #menu do
if i == select then
printCentered("["..menu.text.."]",h/2 + i)
else
printCentered(menu.text, h/2 + i)
end
end
end

local function keyHandler()
event, key = os.pullEvent("key")
if key == 200 and select > 1 then
select = select - 1
elseif key == 208 and select < #menu then
select = select + 1
elseif key == 28 then
menu[select].handler()
end
end

while true do
printMenu()
keyHandler()
end
TheOddByte #2
Posted 15 August 2014 - 06:31 PM
Yes you're using it wrong, when you're doing this

local menu = {
    [1] = { text = "blah", handler = runApp(); }
}
end
handler expects the function runApp to return a value, since you're actually running the function when you're using paranthesis there

So todo this the way you want it you would have to declare handler equal to the function you want to use

local menu = {
    [1] = { "Text here", handler = runApp };
}
aceyo369 #3
Posted 15 August 2014 - 06:40 PM
Thanks a lot man, now I can clarify how to use function in Array, great thanks