Interfacing random C functions from Lua scripts

Tuomo Valkonen <[email protected]>
Newsgroups gmane.comp.window-managers.ion.general
Message-ID <[email protected]>
Every now and then, people ask for access to random C functions
from Lua. Providing access to all of them through Ion is the 
wrong approach that would make Ion itself bloated. But the set
of Lua libraries isn't that big either (but be sure to check
the LuaForge [1]).

So the way to do it in that case, is to provide your own C
bindings. Unfortunately, that's a bit cumbersome, if you have
to write an extra Lua or Ion module in addition to your script.
Fortunately, LuaTCC [2] provides support for inline C code in your
Lua scripts. It is dependent on the Tiny C Compiler (TCC) [3].
As have attached to this email, the example of the oft-requested
'setenv'.

  [1]: http://luaforge.net/

  [2]: http://luatcc.luaforge.net/

  [3]: http://fabrice.bellard.free.fr/tcc/

-- 
Tuomo
setenv.lua (text/plain, 698 B)
require("tcc") -- http://luatcc.luaforge.net/

local LUA_PATH='/usr/local'

local ctx=tcc.new()

ctx:add_include_path(LUA_PATH)
ctx:add_library_path(LUA_PATH)

ctx:compile[[
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <lua.h>
    #include <lauxlib.h>
    int lua_setenv(lua_State *st)
    {
        const char *name=luaL_checkstring(st, 1);
        const char *value=luaL_checkstring(st, 2);
        if(setenv(name, value, 1)!=0){
            lua_pushstring(st, strerror(errno));
            lua_error(st);
        }
        return 0;
    }
]]

ctx:relocate()

os.setenv=ctx:get_symbol('lua_setenv')

-- Test
os.setenv("FOO", "BAR")
print(os.getenv("FOO"))
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.