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. Android学习(二十三)SubMenu 子菜单

    一.SubMenu子菜单 和功能菜单相似,但是可以添加子菜单. 二.实现步骤: 1.通过onCreateOptionsMenu方法创建子菜单,可以通过代码动态创建,也可以通过xml进行创建. 2.通过 ...

  2. passwd(总结)

    1.当前用户是root root用户修改密码 ,直接 passwd[不要输入当前用户密码] 如果修改其他用户密码,需要 passwd 用户名 如: passwd sc 短短的密码,如123也能通过,因 ...

  3. 【Excle数据透视表】如何得到数据透视表中某个汇总行的明细数据

    例如: 现在想得到"北京 汇总"的明细数据,该怎么处理呢? 步骤 右键数据透视表任意单元格→数据透视表选项→启用显示明细数据→确定→单击"北京 汇总"行最后一个 ...

  4. MYSQL总结之sql语句大全

    一.基础1.说明:创建数据库 CREATE DATABASE database-name .说明:删除数据库 drop database dbname .说明:备份sql server --- 创建 ...

  5. 原 [Android]LIstView的HeaderView

    目录[-] (1)添加HeaderView之后尺寸布局被忽略. (2)添加HeaderView之后导致OnItemClickListener的position移位 (3)LayoutInflater的 ...

  6. list集合转换成json类型

    public String gettext(HttpServletRequest request,HttpServletResponse response){ List<xuanhuan_> ...

  7. Redis, Memcache, Mysql差别

    在使用Redis过程中,我们发现了不少Redis不同于Memcached.也不同于MySQL的特征. (本文主要讨论Redis未启用VM支持情况) 1. Schema MySQL: 需事先设计 Mem ...

  8. Atitit.远程接口 监控与木马   常用的api 标准化v2 q216

    Atitit.远程接口 监控与木马   常用的api 标准化v2 q216 1. 木马与远程接口 监控的常用的api2 1.1. 文件复制2 1.2. 屏幕定时截图2 1.3. 邮件发送2 1.4.  ...

  9. 【转】Lua 操作系统库

      转老帖子备份 转自:http://www.cnblogs.com/whiteyun/archive/2009/08/10/1542913.html os.clock () 功能:返回一个程序使用C ...

  10. Centos7 install RabbitMQ

    安装rabbitmq 需要环境上有erlang,没有安装的可以参照下面的内容进行安装: https://www.erlang-solutions.com/resources/download.html ...