Using Lua with C++
edw.is
edw.is
This is the only part of the article I disagree with. I've found that the biggest problem with using Lua in a C++ game is writing code in the "wrong" language, and the mess that can cause. The boundary between Lua and C++ needs solid validation to keep bugs out, and this makes it neither performant nor convenient, so minimising the boundary is important. As soon as code ends up in the wrong language, you generally need to add a large amount of unnecessary boundary code.
An important part of designing a Lua/C++ game for me is having a good mental model of what the "right" language to write any piece of code in is, and only deviating from that when performance mandates.
I feel like I've fallen into a trap of writing the code in C++ first ("because it's fast!") and then porting it to Lua when I realized that I need to write too much "binding" code.
For example, if you're writing a very simple AI, you can write a FSM/Behaviour Tree implementation entirely in Lua and then write AI logic directly in Lua. This way, you won't need to write binding code between Lua/C++ for these FSM/BT implementations.
And then, after you've written some code with these structures, you can see if you need to port it to C++ for performance or not. And if you do, it will be easier to design API since you already know which parts you need to expose.
One thing that makes prototyping in Lua fast is that the code, which looks simple in Lua, can easily become a pretty difficult template meta-programming code in C++.
Having tables as the primary underlying data structure gives it a very LISP-y feel despite having an ALGOL syntax, providing a nice middle ground between the two styles.
I've done quite a few projects where I built a library of C modules to do the heavy lifting for some particular purpose (data in/out mostly), glommed these functions into the LuaVM, then built the application logic, very rapidly and smoothly, in Lua - outcompeting others working in my group with their big fancy stacks of stuff, time and time again.
I think its really important for any developer, whether they are encased in the glories of the browser or otherwise, to understand how to add the Lua VM - to anything - and then use that as a means of productive application development.
Its very rewarding once you get the VM glomming happening and can start accessing everything you need from within your own scriptable execution environment. More programmers should learn this technique, imho - it moves us from being effected clients of someone elses' ball of string and wax, to actually causative developers building architecture that really, really works.
Whether you like Lua or not, building-in a VM for your higher-level application logic is just good architecture.
If anyone reading this wants to see what the fuss is, you can get started very easily with antirez' (Redis fame) simple toy project, LOAD81 - which is a great example of just how powerful things can get when you bring Lua into your life. (http://github.com/antirez/load81.git) - note that this is a great project to learn this technique, but if you do anything interesting in the load81 context - please push it back to LOAD81. :)
[1] https://www.oreilly.com/library/view/creating-solid-apis/978...
Lua is pretty much a "minimal" language which gets things done. It's not perfect, but it certainly doesn't suffer from the bloat which many other languages have.
We can also have a small core team writing C/C++, and then let a wider team loose to build applications with Lua.
I think Python is an example of the same pattern, you write your glue code in Python and the high performance code is in C called by C FFI from Python.
I just wonder how we can write code with development velocity of Python or Lua but actually evaluate extremely fast.
Okay, not workable for every Lua project, but for most it'll be fine.
I completely agree! I feel that I should add thoughts about this into the article.
A lot of people (justifiably) complain that C and C++ are not memory-safe and that it's hard to write readable and safe code in it. Lua allows you to hide the scary parts of C and C++ and write simpler and safer code by default.
This isn't so easy to do in the Javascript jungle, alas.
Happy to read your article, we are very much aligned. I hope your work brings more programmers to the world of Lua ..
Especially when bringing up and testing new hardware and algorithms, it is incredibly useful to to be able to go from "wouldn't it be useful if we could test <insert scenario here>" to a fully automated system test with a few lines of Lua.
- https://luau-lang.org (Lua derivative, interpreted / sandboxed, from Roblox)
- https://terralang.org (Lua JIT compiler)
- https://nelua.io (Lua-syntax -> C compiler (WASM too w/ Emscripten)
- https://github.com/pallene-lang/pallene (Lua AOT compiler)
- https://github.com/teal-language/tl (Teal -> Lua compiler)
- https://typescripttolua.github.io/ (TS -> Lua compiler)
- https://github.com/sumneko/lua-language-server (IDE only typing)
With minimum effort you can get a lot of benefit from using Sumneko's Lua language server in VSCode for near many Lua versions (LuaJIT, PUC-Rio Lua, etc.)
All of the projects serve different purposes, whether you need/love Lua for speed (JIT, for games), low memory usage (AOT, for embedded), or simplicity (all of them).
A recent project involved doing fluidic particulate quantification in an embedded, field portable instrument, which was delivered on time and under-budget - and represented a major revenue source for the customer (40 million dollars worth of orders) when it was shipped. The client was told it "could not be done" with the hardware as specified - not only did we do it with Lua, it has since been widely recognized as the most advanced bit of architecture the company has implemented for its instruments ..
Lua is not just for games. Games are a good place to learn Lua, though.
I am currently prototyping a Lua environment for instrument control in a regulated environment. I've added several customisations and safety mitigations to make it suitable for use, and it works beautifully. One thing I would like is to be able to showcase examples of use in other products.
If you, or anyone else, have any examples I could point people to, to demonstrate existing real-world uses of Lua, that would be really appreciated.
https://www.spectrosci.com/product/fieldlab-58---portable-oi...
This in practice means you have to use Array of 64 byte Structure for your shared data.
Lua is not going to change that. You can hot-deploy C with a .so/.dll without losing performance.
Many simple games don't need it, by the way. A lot of 2D indie games don't do complex enough rendering/physics to warrant a separate thread. This, in turn, makes everything much simpler if your entire game only uses one thread.
I have yet to find similar packages for C SWIG can be used to ease the c-binding coding.
Lua with C/C++ works basically like Python with CFFI, but Lua is much simpler and light weight that you can embed into your projects directly. A perfect combination between glue scripting and heavy lifting code that is small and easy to maintain.
Another way would be to make a minor interpreter modification to have it count byte code instructions executed and terminate execution that way. But then you might run into problems where calls into native functions might take a long time (e.g. string.rep("x", 1000000000)).
So it's not easy and the only solid approach is to have lua run in some external process and kill that using OS limits. You might get away using a thread instead of a process if you use a custom memory allocator to help with cleaning up resources, but I'm not sure if it's safe to terminate Lua that way.
Lua provides the LUA_MASKCOUNT hook type since at least Lua 5.1, which calls the hook every N instructions. See https://www.lua.org/manual/5.1/manual.html#lua_sethook and https://www.lua.org/manual/5.4/manual.html#lua_sethook
The following prints 1 through 10 and then exits using Lua 5.3 and 5.4:
local i = 0
debug.sethook(function ()
i = i + 1
print(i)
if i >= 10 then
os.exit()
end
end, "", 1)
while true do
-- nothing
end
I've never used hooks in practice, though, so I may be missing some caveats beyond the obvious.Regarding time, IIRC the Lua implementation very carefully implements lua_sethook (and related internals) such that you can safely install a hook from a signal handler, at least on common hardware like x86, ARM, etc where pointer assignments are naturally atomic. It can be tricky to make your lua_State context available to a signal handler, though.
Also, unless you isolate the process using system facilities, Lua probably isn't suited to running potentially malicious code as the VM doesn't see enough eyeballs. Looking through the bug history at https://www.lua.org/bugs.html it's apparent that even if you disable all APIs there are occasionally exploitable bugs in the interpreter. I suppose the same is true in practice regarding, e.g., Node--many more eyeballs but the JIT engines are so much more complex that you end up in the same place. (The jury is still out on dedicated WebAssembly engines, but JIT engines are notoriously complex and "memory safe" languages don't help with JIT bugs.)
With sol, it's much easier - you just register function/classes in your C++ code - it's much easier to do than with Lua C API and doesn't require running any "post-processing" steps at all.