Storing a function as a variable?

So I want to be able to use a function to create an NPC:

function create_npc(url,coords,message,event)

The “event” argument is for a function that’s supposed to be stored in the NPC for later use. However, I don’t know how to send a function to be called later on when it’s stored as a variable.

if message_id == hash("end_event") then
	end_event = message.event
	print(end_event)
end
if end_event then
	--something something activate the function
	end_event = nil
end

If anyone could help me with this, that would be great. Thanks ahead of time~

1 Like

Store the actual function within a shared module and then only send a reference to the function in messages?

2 Likes

If event is the variable storing the function you want to execute, simply use:

if (i_want_to_execute_the_function_now) then
    event()
end
3 Likes

In Lua, you can store a function in a variable.
For example, when monkey patching a function:

local oldprint = print
print = function (...)
    oldprint("special message!")
    oldprint(...)
end

However, since you’re also mentioning the “message” table, it’s actually serialized by the engine, and we only support certain built in types. Functions are not supported.

I recommend sending a string or hash, to tell what mode the npc is in, and what function to execute later.

3 Likes

I suggest the same as all above :wink:
I’m solving such callbacks by using a Lua module with a table, where keys are hashes and values are functions to call:

local M = {}
M[hash("my_event")] = function() ... end

then I pass proper hashes via message:

msg.post("#some_script", "callback", {key = hash("my_event")})

and call the proper function when such message is received:

local events = require "somewhere.events"
if message_id == hash("callback") then
    events [message.key]()
end

Code is simplified, I suggest also pre-hashing :wink:
Later you can use some more generic modules/assets for Defold, that would be great for events, such as Broadcast from https://github.com/britzl/ludobits/blob/master/ludobits/m/broadcast.md or Dispatcher from https://github.com/critique-gaming/crit/blob/master/docs/dispatcher.md

4 Likes