Creating C closures from Lua closures
8 days ago
- #Assembly
- #C
- #Lua
- The article discusses bridging the Windows C API to Lua, focusing on creating C callbacks from Lua functions.
- Lua closures (up values) are explained, showing how outer variables are enclosed within functions.
- C lacks closures but can pass data to callbacks via pointers, demonstrated with a simple example.
- The ideal Lua API for bridging involves passing a Lua function to a C callback type, returning a dynamically created C function.
- A naive implementation is shown, storing Lua functions in the Lua registry and calling them from C, but it's limited to one function.
- The solution involves dynamically generating assembly at runtime to create unique C pointers for each Lua function.
- Learning assembly via Visual Studio's debugger and online tools is detailed to understand the necessary instructions.
- The article explains how to generate assembly instructions like `mov` and `jmp` for setting up callbacks.
- A function `generate_function` is implemented to create executable memory with the generated assembly.
- Caveats include inefficient memory use and the need for thread safety and proper memory protection in practice.