Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
Calling functions in C from your Lua script - a first HowTo

Airport FoodThis 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

Of all the subjects I train in, Lua is perhaps the most specialised and niche of them all. Illustration ... on my way back from a private Lua course in Mexico, I changed planes in Mexico City ... and here I am, on line, writing up notes ....





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, updated 2010-06-23)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
U117 - Other Lua Subjects
  [2461] Luac - getting lua to start fast by precompiling - (2009-10-20)
  [1845] Passing a table from Lua into C - (2008-10-18)


Back to
How many cups of coffee?
Previous and next
or
Horse's mouth home
Forward to
Passing a table from Lua into C
Some other Articles
30th November - Santa Trip from Melksham
Lua - IAQ (Infrequently Answered Questions)
Old Piles of the South West
Calling functions in C from your Lua script - a first HowTo
How many cups of coffee?
Lua Course, and the Wiltshire Countryside too
Formatting with a leading + / Lua and Perl
Validating Credit Card Numbers
Job application
4734 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2017: 404 The Spa • Melksham, Wiltshire • United Kingdom • SN12 6QL
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/1844_Cal ... HowTo.html • PAGE BUILT: Sat May 27 16:49:10 2017 • BUILD SYSTEM: WomanWithCat