Passing Tables to Lua Functions
A use case that happens often is the passing of tables to and from Lua functions. How is that handled? There are a few idioms you see over and over again to make it happen. Before discussing the idioms, here's the code:
The Lua Program
Here's the Lua program. As you can see, function tweaktable receives a table argument, converts all values to upper case, counts the values, and puts all that info in a new table that's returned. function tweaktable(tab_in)
local tab_out = {numfields=}
for k,v in pairs(tab_in) do
tab_out.numfields = tab_out.numfields +
tab_out[tostring(k)] = string.upper(tostring(v))
end
tab_out.numfields = tostring(tab_out.numfields)
io.write("At bottom of callfuncscript.lua tweaktable(), numfields=")
io.write(tab_out.numfields)
print()
return tab_out
end print("Priming run")
The C Program
The C program is the same as all the others except stacking arguments to Lua is a little different, and recovering the table passed back from Lua is a little different. The Lua tweaktable() function takes a table as its one and only argument and passes back one table. It passes back a completely different table so there's absolutely no question of the changes being made by reference to the args rather than passback. Start by looking and running the code, and then we'll discuss some of the idioms that make it work...
#include <lua.h> /* Always include this when calling Lua */
#include <lauxlib.h> /* Always include this when calling Lua */
#include <lualib.h> /* Prototype for luaL_openlibs(), */
/* always include this when calling Lua */ #include <stdlib.h> /* For function exit() */
#include <stdio.h> /* For input/output */ void bail(lua_State *L, char *msg){
fprintf(stderr, "\nFATAL ERROR:\n %s: %s\n\n",
msg, lua_tostring(L, -));
exit();
} int main(void)
{
lua_State *L; L = luaL_newstate(); /* Create Lua state variable */
luaL_openlibs(L); /* Load Lua libraries */ if (luaL_loadfile(L, "callfuncscript.lua")) /* Load but don't run the Lua script */
bail(L, "luaL_loadfile() failed"); /* Error out if file can't be read */ if (lua_pcall(L, , , )) /* PRIMING RUN. FORGET THIS AND YOU'RE TOAST */
bail(L, "lua_pcall() failed"); /* Error out if Lua file has an error */ printf("In C, calling Lua->tweaktable()\n");
lua_getglobal(L, "tweaktable"); /* Tell it to run callfuncscript.lua->tweaktable() */
lua_newtable(L); /* Push empty table onto stack table now at -1 */
lua_pushliteral(L, "fname"); /* Push a key onto the stack, table now at -2 */
lua_pushliteral(L, "Margie"); /* Push a value onto the stack, table now at -3 */
lua_settable(L, -); /* Take key and value, put into table at -3, */
/* then pop key and value so table again at -1 */ lua_pushliteral(L, "lname"); /* Push a key onto the stack, table now at -2 */
lua_pushliteral(L, "Martinez"); /* Push a value onto the stack, table now at -3 */
lua_settable(L, -); /* Take key and value, put into table at -3, */
/* then pop key and value so table again at -1 */ if (lua_pcall(L, , , )) /* Run function, !!! NRETURN=1 !!! */
bail(L, "lua_pcall() failed"); printf("============ Back in C again, Iterating thru returned table ============\n"); /* table is in the stack at index 't' */
lua_pushnil(L); /* Make sure lua_next starts at beginning */
const char *k, *v;
while (lua_next(L, -)) { /* TABLE LOCATED AT -2 IN STACK */
v = lua_tostring(L, -); /* Value at stacktop */
lua_pop(L,); /* Remove value */
k = lua_tostring(L, -); /* Read key at stacktop, */
/* leave in place to guide next lua_next() */
printf("Fromc k=>%s<, v=>%s<\n", k, v);
} lua_close(L); /* Clean up, free the Lua state var */
return ;
}
The preceding code yields the following output:
slitt@mydesk:~$ ./callfunc
Priming run
In C, calling Lua->tweaktable()
At bottom of callfuncscript.lua tweaktable(), numfields=
============ Back in C again, Iterating thru returned table ============
Fromc k=>fname<, v=>MARGIE<
Fromc k=>lname<, v=>MARTINEZ<
Fromc k=>numfields<, v=><
slitt@mydesk:~$ 转自:http://www.troubleshooters.com/codecorn/lua/lua_c_calls_lua.htm

C调用Lua中的函数解析table的更多相关文章

  1. ulua c#调用lua中模拟的类成员函数

    项目使用ulua,我神烦这个东西.lua单纯在lua环境使用还好,一旦要跟外界交互,各种月经不调就来了.要记住贼多的细节,你才能稍微处理好.一个破栈,pop来push去,位置一会在-1,一会在-3,2 ...

  2. Lua中的函数

    [前言] Lua中的函数和C++中的函数的含义是一致的,Lua中的函数格式如下: function MyFunc(param) -- Do something end 在调用函数时,也需要将对应的参数 ...

  3. 在C++中调用DLL中的函数 (3)

    1.dll的优点 代码复用是提高软件开发效率的重要途径.一般而言,只要某部分代码具有通用性,就可将它构造成相对独立的功能模块并在之后的项目中重复使用.比较常见的例子是各种应用程序框架,ATL.MFC等 ...

  4. 在C++中调用DLL中的函数(3)

    1.dll的优点 代码复用是提高软件开发效率的重要途径.一般而言,只要某部分代码具有通用性,就可将它构造成相对独立的功能模块并在之后的项目中重复使用.比较常见的例子是各种应用程序框架,ATL.MFC等 ...

  5. 在 lua 中实现函数的重载

    在 lua 中实现函数的重载.注:好吧,lua中原来可以实现重载...local function create() local arg_table = {} local function dispa ...

  6. 在VS2012中采用C++中调用DLL中的函数 (4)

    这两天因为需要用到VS2012来生成一个DLL代码,但是之前并没有用过DLL相关的内容,从昨天开始尝试调试DLL的文件调用,起初笔者在网络上找到了3片采用VSXXX版本进行调试的例子,相关的内容见本人 ...

  7. 在C++中调用DLL中的函数 (2)

    应用程序使用DLL可以采用两种方式: 一种是隐式链接,另一种是显式链接.在使用DLL之前首先要知道DLL中函数的结构信息. Visual C++6.0在VC\bin目录下提供了一个名为Dumpbin. ...

  8. 在C++中调用DLL中的函数

    如何在C++中调用DLL中的函数 应用程序使用DLL可以采用两种方式:一种是隐式链接,另一种是显式链接.在使用DLL之前首先要知道DLL中函数的结构信息.Visual C++6.0在VC\bin目录下 ...

  9. 【原创】在VS2012中采用C++中调用DLL中的函数(4)

    这两天因为需要用到VS2012来生成一个DLL代码,但是之前并没有用过DLL相关的内容,从昨天开始尝试调试DLL的文件调用,起初笔者在网络上找到了3片采用VSXXX版本进行调试的例子,相关的内容见本人 ...

随机推荐

  1. 使用Gulp定制前端开发环境

    1.安装package.json中依赖了的组件 npm install 2.来到本地路径,创建工程配置文件 npm init 3.本地安装gulp npm install gulp --save-de ...

  2. 【Django】其他项目导入到Pycharm无法使用,报错:Error: Django is not importable in this environment

    导入项目后如下:项目名称那出现一个小叉 点击启动后提示错误: 那是由于运行环境的路径没有指向python的安装路径,如下图即可解决问题

  3. Hibernate核心类和接口具体介绍

    一.hiobernate核心类和接口预览图 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGxnZW4xNTczODc=/font/5a6L5L2T/fo ...

  4. 两个页面js方法兼容

    1. a.js页面 //Js获取Url参数 function request(paras) { var url = location.href; var paraString = url.substr ...

  5. 类中的internal成员可能是一种坏味道

    前言 最近除了搞ASP.NET MVC之外,我也在思考一些编程实践方面的问题.昨天在回家路上,我忽然对一个问题产生了较为清晰的认识.或者说,原先只是有一丝细微的感觉,而现在将它和一些其他的方面进行了联 ...

  6. 【CODEFORCES】 A. Initial Bet

    A. Initial Bet time limit per test 1 second memory limit per test 256 megabytes input standard input ...

  7. Spring学习二----------IOC及Bean容器

    © 版权声明:本文为博主原创文章,转载请注明出处 接口 用于沟通的中介物的抽象化 实体把自己提供给外界的一种抽象化说明,用以由内部操作分离出外部沟通方法,使其能被修改内部而不影响外界其他实体与其交互的 ...

  8. 高盛CEO致大学毕业生:要与有野心的人为伍

    我认为讲的非常棒.年轻人就要这样. 高盛集团首席运行官(CEO)劳尔德-贝兰克梵(Lloyd Blankfein)周四在曼哈顿贾维茨中心參加了拉瓜迪亚社区大学的第41届毕业典礼并发表演讲.在面向约10 ...

  9. 千万级的大表!MySQL这样优化更好

    对于一个千万级的大表,现在可能更多的是亿级数据量,很多人第一反应是各种切分,可结果总是事半功倍,或许正是我们优化顺序的不正确.下面我们来谈谈怎样的优化顺序可以让效果更好. MySQL数据库一般都是按照 ...

  10. Java编程之路相关书籍(三个维度)

    一.关于Java的技术学习.能够依照以下分三个维度进行学习 : (1)向下发展,也就是底层的方向 建议看<深入Java虚拟机>.<Java虚拟机规范>.<Thinking ...