briba
briba

Reputation: 2987

Calling a C function from Lua

I'm trying to call a function from a C project but I don´t know how to do it.

Here is my code ("treatments.c"):

#include <string.h>
#include "lua.h"
#include "lauxlib.h"

static int treatments_load_image (lua_State * L) {
    lua_pushnumber(L,10);
    return 1;   
}

static const luaL_Reg RegisterFunctions[] =
{
    { "treatments", treatments_load_image },
    { NULL, NULL }
};

int luaopen_treatments(lua_State *L)
{
    lua_newtable(L);

    #if LUA_VERSION_NUM < 502
        luaL_register(L, NULL, LuaExportFunctions);
    #else
        luaL_setfuncs(L, LuaExportFunctions, 0);
    #endif

    return 1;
}

In my .lua file, I´m trying to do something like this:

local treatments = require 'treatments'

And I get the error below:

lua: run.lua:15: module 'treatments' not found:
no field package.preload['treatments']
no file './treatments.lua'
...

The ".c" file is in the same folder than ".lua" file. I'm not using any MAKEFILE file.

If it helps, I'm using Lua 5.1 =)

Thanks!!

Upvotes: 1

Views: 440

Answers (2)

user2033018
user2033018

Reputation:

Lua's require deals with files containing Lua code or shared libraries in the case of C. You need to compile the C source code into a shared library and then load that, which should "return" a table (i.e. push it onto the stack), as usual.

Upvotes: 2

secmask
secmask

Reputation: 8107

The ".c" file is in the same folder than ".lua" file. I'm not using any MAKEFILE file

No, you must build your c source file into shared library (dll for windows, or so for linux), then put that shared library in lua package.cpath, see http://lua-users.org/wiki/ModulesTutorial

Upvotes: 3

Related Questions