Root/lua/examples/lua_calls_C3/candy.c

1
2/* This is the third (of three) examples of calling from
3a Lua script to a C library. In this example, we have
4registered multiple C functions with the Lua, and we have
5also passed in a table which is intrinically much harder
6to handle as it doesn't map directly to a C type. */
7
8#include "lua.h"
9#include "lauxlib.h"
10#include <stdio.h>
11
12/* The peardrop function is called with a single
13numeric parameter, and it returns a number */
14
15static int peardrop ( lua_State *L) {
16        printf ("lua SIE's test\n");
17        double trouble = lua_tonumber(L, 1);
18        lua_pushnumber(L, 16.0 - trouble);
19        return 1;
20        }
21
22/* The humbug function is called with a TABLE as
23its parameter (or it should be!). It extracts the
24element with the key "hq", and returns 123 more
25than that number (the sum added is just done to
26demonstrate the C doing something! */
27
28static int humbug ( lua_State *L) {
29        printf ("Enter humbug function\n");
30
31        /* Is it a table? */
32        if (lua_istable(L,-1)) {
33                printf("Table passed to humbug\n");
34
35                /* Looking up based on the key */
36                /* Add key we're interested in to the stack*/
37                lua_pushstring(L,"hq");
38                /* Have Lua functions look up the keyed value */
39                lua_gettable(L, -2 );
40                /* Extract the result which is on the stack */
41                double workon = lua_tonumber(L,-1);
42                /* Tidy up the stack - get rid of the extra we added*/
43                lua_pop(L,1);
44
45                /* We can now use the result */
46                lua_pushnumber(L, workon + 123.0 );
47        } else {
48                printf("Not a Table passed to humbug\n");
49                lua_pushnumber(L, 12.0 );
50        }
51        return 1;
52        }
53
54/* This registers "dothis" and "dothat" with Lua, so that when
55they're called they run the humbug and peardrop functions respectively */
56
57int luaopen_candy ( lua_State *L) {
58        static const luaL_reg Map [] = {
59                {"dothis", humbug},
60                {"dothat", peardrop},
61                {NULL,NULL}
62                } ;
63        /* dothis and dothat are put in the extratasks table */
64        luaL_register(L, "extratasks", Map);
65        return 1;
66        }
67         
68

Archive Download this file

Branches:
master



interactive