[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: C under Lua
- From: Javier Guerra <javier@...>
- Date: Wed, 22 Feb 2006 01:07:26 -0500
Hi
have anybody else seen this: ?
http://fabrice.bellard.free.fr/tcc/
it's a fast C compiler, it compiles, links and loads code in one pass. it's
supposed to make it possible to use C as a scripting language, without a VM
(it compiles to machine language, just like any other C compiler).
so... i've written a Lua wrapper, just to see what would be possible to do
with it.
tcc.compile (Ccode, funcname(s) [, libname(s)])
where Ccode is a string with the C code, funcname(s) is either a string or an
array of strings with the names of the functions to be exported, and
libname(s) is an optional string or array of strings with the names of any
external library to be dynamically loaded (like -lxxx parameter to a CLI
compiler)
if funcname is a string, then tcc.compile() returns a funcion; if it's a
table, it returns a table of functions (could be used a module)
trivial example:
require "lua_tcc"
hello = tcc.compile ([[
void hi (void) {
printf ("Hello World!\n");
}
]], "hi")
hello() => Hello World!
or:
add = tcc.compile ([[
#include "lua"
int add (lua_State *L) {
lua_pushnumber (L, luaL_checknumber (L, 1) + luaL_checknumber (L, 2));
return 1;
}
]], "add")
print (add (2,4)) => 6
or a table of functions:
m = tcc.compile ([[
#include "lua"
int add (lua_State *L) {
lua_pushnumber (L, luaL_checknumber (L, 1) + luaL_checknumber (L, 2));
return 1;
}
int sub (lua_State *L) {
lua_pushnumber (L, luaL_checknumber (L, 1) - luaL_checknumber (L, 2));
return 1;
}
]], {"add", "sub"})
print (m.add(2,4)) => 6
print (m.sub (5,2)) => 3
link to C libraries: (adapted from a TCC example)
x = tcc.compile ([[
#include <X11/Xlib.h>
void x_size (void)
{
Display *display;
Screen *screen;
display = XOpenDisplay("");
if (!display) {
fprintf(stderr, "Could not open X11 display\n");
exit(1);
}
printf("X11 display opened.\n");
screen = XScreenOfDisplay(display, 0);
printf("width = %d\nheight = %d\ndepth = %d\n",
screen->width,
screen->height,
screen->root_depth);
XCloseDisplay(display);
}
]], "x_size", "X11")
sounds fun, eh? of course, with Mike's LuaJIT going so well, it's of limited
value. also, being C code, it's easy to go segfault.
anybody can think of a use for this? if there's any interest, i'll put it in
LuaForge.net
--
Javier
Attachment:
pgpTDxhMSahsA.pgp
Description: PGP signature