Hardware Design: SIE
Sign in or create your account | Project List | Help
Hardware Design: SIE Git Source Tree
Root/
| 1 | |
| 2 | /* This is the third (of three) examples of calling from |
| 3 | a Lua script to a C library. In this example, we have |
| 4 | registered multiple C functions with the Lua, and we have |
| 5 | also passed in a table which is intrinically much harder |
| 6 | to 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 |
| 13 | numeric parameter, and it returns a number */ |
| 14 | |
| 15 | static 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 |
| 23 | its parameter (or it should be!). It extracts the |
| 24 | element with the key "hq", and returns 123 more |
| 25 | than that number (the sum added is just done to |
| 26 | demonstrate the C doing something! */ |
| 27 | |
| 28 | static 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 |
| 55 | they're called they run the humbug and peardrop functions respectively */ |
| 56 | |
| 57 | int 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 |
Branches:
master
