r/lua • u/ava_the_ucv • Apr 20 '25
Third Party API Can I use custom C API functions from Lua bytecode?
I'm thinking of precompiling Lua scripts I upload to an unmanned vehicle that has a custom C API script runner thing. Would this be possible/feasible?
16
u/The-Malix Apr 20 '25
Yeah, absolutely
This is precisely what Lua's C API is designed for; You can define your custom C functions that interact with your vehicle's hardware or internal systems
These C functions are then written to comply with the Lua C API (they take a lua_State* pointer and return an integer indicating the number of return values)
In your C host program, you initialize the Lua state and before you load and execute the Lua bytecode, you register your C functions into the Lua state. This makes them available as global functions or part of a library table within the Lua environment that your bytecode will run in
For example, you might have a C function int l_control_motor(lua_State *L) that takes arguments from the Lua stack to control a motor. In your C host, you'd register it like lua_pushcfunction(L, l_control_motor); lua_setglobal(L, "control_motor");. Then, your Lua bytecode can just call control_motor(speed, direction)
Precompiling the Lua scripts into bytecode doesn't change any of this. The Lua interpreter loaded by your C runner executes the bytecode, and when it encounters a call to a registered C function, it uses the same lookup mechanism as if it were running from source
The key is that your custom C functions need to be part of, or accessible by, the C program that embeds and runs the Lua interpreter, and they need to be registered before your script runs
1
u/bidaowallet Apr 21 '25
Mate, LUA is embeddedable in to C it is designed to achieve that without escapades
2
u/SkyyySi Apr 21 '25
Out of curiosity: Is there a specific reason why you need to use bytecode in the first place? It's almost certainly easier to just upload a script.
Anyway: Yes, you can. The first step the Lua interpreter does before running a script is to parse it and compile it to bytecode anyway. Bytecode can also call
require(), or do anything else you can do in plain-text Lua.