14-07-2021

In this tutorial we go over calling Lua functions from C.Twitter: https://twitter.com/KarmaKilledTC.

  • Initial Examples
  • More examples

Introduction

Allowing users to extend your apps with scripts it is an amazing feature. There are many languages for this purpose, but Lua is the choice today, it is powerful and easy to embed.

Lua is an important tool for many industries, it has been used inside Game Engines, Databases like Redis, and HTTP servers like Nginx, powering users to extend their features.

I will show you some essential but complete examples in how to work with Lua, I will not cover some deep concepts behind the language, installation and other topics like LuaJIT.

Another thing that I will not cover is how to compile and link your app with Lua library, if you know a little about C you can do it with almost no effort using the official manual, the goal here is talking about examples and how to use the API. But if you do not know how to do, check my repository link with examples at the end of this article.

Installation

How I said I do not cover the installation of Lua development libraries, because it varies and depends on your platform.You can look at the installation guide in the official website here.

Some Lua Concepts

It is important you understand at least one concept before, the virtual stack. Lua uses a virtual stack to pass values to and from C.

All communication between lua code and your application works using the virtual stack. You push data from C for defining global variables, tables, functions and function arguments. Lua VM will be made all this data available inside Lua script. When a Lua code calls a C function, for example, inside the function you have to recover the arguments and push the result again to Lua.

Another example is when you need to call from C a Lua function. You have to call an API function to let Lua knows which function should be put onto the stack to be available to C call it.

Now you are ready to start coding.

Starting Lua VM

The basic code that we need to call when we use Lua C API is as follow. We start declaring a lua_State pointer and initialize it with luaL_newstate() function.

Note that versions before 5.3 lua_open() is used instead.

It is our pointer to our Lua Virtual Machine and this lua_State store all data that we share between Lua and C. We can have many Lua states to run scripts with different contexts.

After opening a state, we are ready to call functions from Lua API.

One important function to be called is luaL_openlibs, it makes available the Lua Standard Library for the code that we will run afterwards. It is not a requirement, but without this you will not be able to call functions from libraries like math, io, string, utf8, inside Lua code.

You can also open only the libraries that you know it will be useful or safe to allow scripts to call, see the example bellow, more information here.

After using the lua state, when you do not need to execute anything else, you have to close the state with:

Initial Examples

I wrote some examples of basic operations like running Lua code from a string, loading a script file, exposing variables and C functions to Lua code, recovering the values from global variables inside the Lua code and calling Lua function in C.

Initializing Lua VM

Here is our first example, it is a starting point for using Lua with C.

Calling C From Lua Code

Let's dissect the code structure. We start adding the headers:

Start a new Lua state:

With L state your now able to call Lua C API.

Open the Lua standard libraries, like math, string, utf8, io, etc.:

After using Lua we need to close the state:

Running Lua code

This example shows how to load a Lua code from string and run it.

The new things here are the API functions: luaL_loadstring, that is in charge of loading the code chunk on the top of the stack, lua_pcall is in charge of running the code in the stack, and if the execution is successfull, we remove the code from the top(lua_gettop) of the stack with lua_pop.

More examples

Before continuing the examples I have to explain some updates made in the article.

After the feedback that I received, I decided to make the following examples more clear and simple using some macros available from Lua API.

The following changes were made:

  • Instead of using lua_pcall, luaL_loadstring, and luaL_loadfile, I modified the code to use:
    • luaL_dostring, which is equivalent to calling lua_pcall and luaL_loadstring
    • luaL_dofile, which is equivalent to calling lua_pcall and luaL_loadfile
    • use lua_pcall only when I do not run the function just after loading a file or a string.

All those macros use LUA_MULRET, which is an argument that tells lua_pcall that it must expect a variable number of returned values.

Another point is that when we call lua_pcall or its variants, a result is returned indicating if the call was successfully executed or not. We can use the constant LUA_OK to check if there is a success or not. When an error happens during lua_pcall, it returns a different value of LUA_OK and puts the error on the top of the stack. We are able to get this error using lua_tostring(L, lua_gettop(L)).

In this article I do not use lua_call because it is a non-protected way to call a function, its use implies that Lua will call a panic function and then call abort. It is possible to handle those errors settings a new panic function with lua_atpanic, but it is not covered in this article.

Using the protected call, any error will make Lua call longjmp, recover from the most recent active recovery point and set the error on top of stack.

Exposing a Simple Variable

It is really common to need to expose some variables for Lua code, and it is simple to do this:

We use here lua_pushinteger to put an integer on the top of the stack and after it, we use lua_setglobal to get this value and set as a global variable named as answer.

After exposing the variable we can use it inside the Lua code.

Note: For more complex types and structures, check Lua manual.

Exposing a Single Function to Lua

This example is a little bit more complex, I added some comments inside the code to explain the more important lines.

This example is similar to the exposing variables, but here we push a function pointer instead of an integer value.

Exposing Functions to Lua with Namespace

Lua

Calling C From Lua Example

We use a table to create a namespace, we put all functions inside this table.

Running a Lua Script

The only difference between running code from string or file it is that we use luaL_loadfile instead of luaL_loadstring.

Getting a Global Variable from Lua

Calling C From Lua Meaning

Retrieving values from a Lua script it is a good way of configuring your app.

Note that we can only get the variable after running the Lua code.

Calling a Lua Function in C

Calling a function defined in a Lua code it is pretty similar of getting a variable, but to execute the function you must check if it is a function on the top of the stack with lua_isfunction and call it with lua_pcall. If it is successfully executed you have to remove from the stack with lua_pop(l, lua_gettop(l)).

Calling a Lua Function in C with Arguments and Return Value

When you call a function defined in Lua, you can pass arguments values and get the return value. To do that you need put onto the stack the list of arguments after putting the function on the stack. After running the function you can check on the top of the stack a get the return value.

Example of Error Handling

Calling C From Lua

A simple way to handle errors when calling a function:

Calling C From Lua Game

The End

Calling C From Lua Youtube

There is much more about this topic, you can learn more about Lua in the official manual, LuaJIT is another important topic, that it is a way to use Lua with a better performance. If you are interested in game development, check Love2D that is an amazing tool. Finally, check my repository with all examples. I hope it will be useful for you.

Thank you!

Extra Resources