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

Calling a function that is linked in a table

Started by mlewelt, 07 July 2013 - 10:07 AM
mlewelt #1
Posted 07 July 2013 - 12:07 PM
I want to call a function via : event, button, x, y = os.pullEvent("mouse_click")
different values of y represent different functions.
the functions are declared normally:

function normal()
print("this function is declared normally")
end
i want to store the name of the function inside a tabel and then run the function via running the key as y from .pullEvent.
This will probably sound confusing so here is an example of what i mean:

function a()
print("a")
end
function b()
print("b")
end
local tabel = {
[1] = a(),
[2] = b()
}
event, button, x, y = os.pullEvent("mouse_click")
then i wanna call the function via interpreting the y from .pullEvent as the key.
so something like:

run tabel[y]
but i dont know how to do this. i searched almost an hour for a solution, but didnt find anything.
i also know that for this example i could just use two if- statements to check whether the y is 1 or 2 but i want to know if this is possible in general and if you have more variables.
i appreciate any help and thank you for your time investment.
Lyqyd #2
Posted 07 July 2013 - 02:19 PM
Split into new topic.

You were pretty close. When you store the function values in the table, don't use the parentheses:


function a()
 --do stuff
end

local tableOfFunctions = {
  [1] = a,
}

--or just tableOfFunctions = {a}, since it will automatically get the index 1.

tableOfFunctions[1]()
mlewelt #3
Posted 07 July 2013 - 02:21 PM
oh dammit :D/>
well thanks for your fast helpfull answer!
AgentE382 #4
Posted 07 July 2013 - 03:02 PM
Better solution: Index your functions based on y-axis.


function a()
    print("a")
end

function b()
    print("b")
end

local functionTable =
{
    [3] = a,    -- Your table doesn't have to be a sequence.
    [5] = b,    -- Just use the y-axis as an index.
    [6] = b	 -- You can assign functions to multiple y-coordinates.
}			   -- Your on-screen buttons are probably more than 1 pixel
			    --	 thick, right?
    
event, button, x, y = os.pullEvent("mouse_click")

functionTable[y]()    -- Index directly with "y" and call the function.


EDIT: As a side note, is anyone else having this much trouble with the code tags? It's messing up my spacing and random junk like that.
Lyqyd #5
Posted 07 July 2013 - 03:19 PM
That's exactly what he was talking about doing, he just didn't know the right syntax to do it. I demonstrated the correct syntax, and my example is easily translatable to the code example he provided.