Member-only story

Super simple example of adding Lua to C++

Dale Thomas
3 min readMar 12, 2022

A minimal example of adding scripting to your C++ project

Photo by Max Duzij on Unsplash

This article was born out of two particular frustrations I have with learning new things. First, I need to start with a very rough, overall, global idea of what it’s all about, before I learn the details. Second, I want to learn from concrete examples, rather than abstract musings.

When I decided I wanted to add scripting capability to my C++ project, I settled on Lua and looked for good introductory tutorials. However, even the simplest went into too much detail for an ‘introduction’.

So, here is a super simple minimal example of how to connect Lua to C++. It does no error checking and there are no bells or whistles. But it does show you what it’s all about and how to do the basics. This code will get you up and running in a few minutes.

I will not show you how to link the Lua library or set up include paths, because that depends on your operating system and development environment, so you’ll have to work it out yourself. Start here.

Anyway, here is what the output of our program will be:

Hello from C++!num = 42, str = From Lua to C++Hello from Lua!num = 73.0, str = From C++ to Lua

Yes, that’s right, I’m starting with the output. We have two functions being called. One is a C++ function being called from Lua, and the other is a Lua function being called from C++. And there are parameters being passed through both ways.

So, you can understand what we’re heading towards. As you can see, it’s a simple program but it shows the basic functionality of calling Lua functions from C++ and vice versa.

Now, here is the C++ code:

And here is the Lua script:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Dale Thomas
Dale Thomas

Written by Dale Thomas

Scifi writer, roboticist, and game developer, 2x Quora Top Writer. I write about writing speculative fiction, computer graphics, AI, evolution, and programming.

No responses yet

Write a response