lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

I'd make the Lua script return a function that receives the plugin as a parameter, i.e.

return function(plugin)
    plugin:dispatchEvent('name')
end

so you can call it with the correct plugin instance from C.

Andre

On 2023-11-29 9:47, Diederick Huijbers wrote:
Hi,

I'm working on a project where I'm integrating Lua into a C app. The C app uses plugins where a plugin can use a .lua file to implement some of its logic. Each plugin is represented by a C based instance of a `struct rx_plugin` and a metatable with the same name. The C application keeps an array of the loaded plugins and manages its memory.

I would like to allow the user to create a .lua file for each plugin. The user should be able to communicate from Lua to C through the plugin instance that is allocated/deallocated in C. For example, in C the user can call a function like `rx_plugin_dispatch_event(rx_plugin* ctx, const char* name)` which will call functions that have been registered with the plugin; e.g. a typical event dispatcher.

I was thinking of creating a metatable (in C) and setting a global userdata with this metatable and the variable name "plugin", so that you can use `plugin:dispatchEvent("name")` from Lua. However, because I'm loading multiple .lua scripts and executing them via `luaL_dofile()` each `plugin` variable will overwrite the previous one.

I found this StackOverflow <https://stackoverflow.com/q/61683579> which describes a similar issue for Lua 5.1, I'm working with Lua 5.4.6 where things work differente regarding globals if I'm right. How can I implement this in C and Lua 5.4.6? I'm also wondering if there are other approaches or patterns for what I'm trying to achieve?

Thanks,
roxlu