lua-users home
lua-l archive

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



On 29 Nov 2023, at 09:47, Diederick Huijbers <diederickh@gmail.com> wrote:

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 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?

It sounds from your basic description that there is no need for direct communication/access between Lua code in different plugins, is that correct?  If so, then I would recommend simply instantiating a new lua_State for each plugin and adding the lua_State pointer to your rx_plugin structure.  That way each plugin is isolated.

Regards,
Chris

Chris Smith <space.dandy@icloud.com>