summaryrefslogtreecommitdiff
path: root/md/writeup/embedding_lua_in_c.md
blob: 7dea5334981aa85b3b003c35c5795cbab6992794 (plain) (blame)
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
title:Embedding Lua in C
keywords:lua,c,embed

# Embedding Lua in C
Bedimming lua in you C programs is can be done in few minutes.
Many examples is in lua-users.org.

First thing to write is module and then compile everything with lua precompiled lib.

```c
int module_register(lua_State*);
void module_print(lua_State*);
int module_getone(lua_State*);
 
int module_gc(lua_State*);
int module_tostring(lua_State*);
 
static const luaL_reg module_methods[] =
{
    //{,(void *)},
    {"print",   (void *)module_print},
    {"getone",  (void *)module_getone},
    {0,         0}
};
 
static const luaL_reg module_meta[] = 
{
    {"__gc",        (void *)module_gc},
    {"__tostring",  (void *)module_tostring},
    {0, 0}
};
```


to make printf("%s\n") available in lua

```c
void module_print( lua_State *L)
{
    int argc = lua_gettop(L);
    int n;
    for (n=1; n <= argc; n++) printf("%s\n", lua_tostring(L, n));
}
```


next one function that have return value 1

```c
int module_getone(lua_State *L)
{
    int x=1;
    lua_pushnumber(L, x);
    return 1;
}
```


and easy to compile if needed.

```sh
gcc -c module.c
gcc module.o main.c -o main -llua
```

## Links
http://lua-users.org/wiki/SampleCode

## Downloads
lua_embed.zip -
2KiB - http://archive.main.lv/files/writeup/embeding_lua_in_c/lua_embed.zip