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

[Question] [Lua] How do I parse in Commands? [SOLVED]

Started by MathManiac, 21 May 2012 - 12:45 AM
MathManiac #1
Posted 21 May 2012 - 02:45 AM
Hello,

I am trying to make a dynamic menu event API, however I need to do one thing: Parse in functions. How do I explain this better….
function doSomething(keycode)
-- Add some code here
end
someAPI.addOnKeyEvent(doSomething)

I've seen somebody declaring it before, so I know it's possible. The main problem is DEFINING the function! What do I put in when defining it? eg.

function addOnKeyEvent(-[[ What do I put here?]]-)
  - Code Here
end

Thanks,
Math

Solution: it works just as variables. Thanks!
Xtansia #2
Posted 21 May 2012 - 05:23 AM
Something kinda like this:
--Some API:

local listeners = {}  --Where we keep the listeners

function addKeyListener( listener )  --Listener is the function we are passing
    listeners[#listeners + 1] = listener  --Add the listener to our table
end

function queueKeyEvent( key )  --Pass the key to all listeners
    for i = 1, #listeners do  --Loop through all listeners
        listeners[i]( key )  --Call the listener function passing in key
    end
end

----------

--Some Program:

function myKeyListener( keyEvent )  --Our test listener function
    print("Hello From My Listener")  --Some print statements
    print("Received Key: " .. keyEvent)
end

someAPI.addKeyListener(myKeyListener)  --Pass the function in to be added to the table
someAPI.queueKeyEvent( "A" )  --Queue a key event
MathManiac #3
Posted 21 May 2012 - 03:33 PM
Something kinda like this:
-snip-

Ah, that makes sense, because variables can hold anomynous functions, such as this:
someVar = function() -[[ do stuff ]]- end

SOLVED
Thanks for your help!