This short article shows you how to call a function that's written in C from a program written in Lua, how to write the function that's called, and how to turn it into an appropriate library and load that library. It then goes on (as a second example) to show you how to pass variables from the Lua script to the C function, and how to pass the result back.
There are a number of examples of calling C from Lua in books, and on web sites, but I wasn't able to find a simple "first steps, everything shown" example - so that's what I set out to do here
First Example. Lua calls C, which runs and returns to Lua
the Lua:
package.cpath = "./?.so"
require "fromlua"
print("hello")
cstuff.dothis()
print ("It's run da C code!")
The C:
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <stdio.h>
static int myCfunc ( lua_State *L) {
printf ("Roses are Red\n");
return 0; }
int luaopen_fromlua ( lua_State *L) {
static const luaL_reg Map [] = {
{"dothis", myCfunc},
{NULL,NULL} } ;
luaL_register(L, "cstuff", Map);
return 1; }
And the compiler instruction to build the library:
gcc -o fromlua.so -shared fromlua.c
The first two lines of the Lua code tell Lua to REPLACE the library path with .so files in the current directory. This is great for testing but you'll want to also consider library directories in a real live program.
The C function who's name is the same as the required module, preceeded by
luaopen_ is run as the module is
requireed, and it defines a Map which tells the interface the names of various Lua function calls, and the equivalent function name that that map to in C. In this case, the lua function
dothis maps to the C function
myCfunc. The map is then registered with Lua, into a table named as the second parameter to the
luaL_register call.
We've now defined where the library is to be found, loaded it, and told Lua about it. All that remains is for us to call the function from the Lua. All functions called in this way return a static int ( the number of values returned) and take as a parameter a Lua stack pointer - although in this first example we return nothing (0) and do nothing with the Lua stack passed in - we just print "Roses are Red" to show we're here. And indeed the code runs like this:
[trainee@easterton one]$ lua top.lua
hello
Roses are Red
It's run da C code!
[trainee@easterton one]$
Second Example - calling C from Lua, passing values in and returning a result.
Here's the Lua code, with the additional use of parameters:
package.cpath = "./?.so"
require "luapassing"
print("hello")
value = 10
summat = cstuff.dothis(value)
print ("It's run da C code!")
print ("Values in Lua now",value, summat)
And here's the luapassing.c source code file:
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <stdio.h>
static int myCfunc ( lua_State *L) {
printf ("Roses are Red\n");
double trouble = lua_tonumber(L, 1);
lua_pushnumber(L, 16.0 - trouble);
return 1; }
int luaopen_luapassing ( lua_State *L) {
static const luaL_reg Map [] = {
{"dothis", myCfunc},
{NULL,NULL} } ;
luaL_register(L, "cstuff", Map);
return 1; }
The code is very similar, but you'll notice six additions - in the Lua:
a) We have added a parameter to the call to dothis in the Lua
b) We have added an assignment to collect a return value from the C
c) We have printed out these values
and in the C:
d) We have used lua_tonumber to collect a numeric value that was passed from the Lua to the C; you'll note that all such numbers are treated as doubles. The parameter "1" indicates 1 down - i.e. top of - the state stack.
e) We have performed a calculation (representative of something being done in the C code) and pushed the result of this back onto the Lua state stack so that it can be picked up once we have returned from the C to the Lua
f) We have changed
return 0 into
return 1 to indicate that one result is being returned.
Running the code ...
[trainee@easterton two]$ lua passing.lua
hello
Roses are Red
It's run da C code!
Values in Lua now 10 6
[trainee@easterton two]$
Although the calling up of C code from within Lua is not the most common of uses of Lua for the typical scripter, the question of "how do I" arose on today's
public Lua course and I was very happy to put the example together. Source code (including additional comments) is available:
•
first Lua example and
the associated C code
•
second Lua example and
the associated C code
There is also a
follow up article available which includes a demonstration of registering several C functions with Lua, and passing a table from Lua into C, making use of individual members of that table within the C.
(written 2008-10-17 18:02:33)
Associated topics are indexed under
U117 - Other Lua Subjects
Some other Articles
30th November - Santa Trip from MelkshamLua - IAQ (Infrequently Answered Questions)Old Piles of the South WestPassing a table from Lua into CCalling functions in C from your Lua script - a first HowToHow many cups of coffee?Lua Course, and the Wiltshire Countryside tooFormatting with a leading + / Lua and PerlValidating Credit Card NumbersJob application