Lua笔记(8)——C API对table的操作

先看下面的C程序(hello.c):

#include <stdio.h>
#include <stdlib.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main(void)
{   
    lua_State *L = luaL_newstate();

    luaL_openlibs(L);

    lua_getglobal(L, "io");
    lua_getfield(L, -1, "write");
    lua_pushstring(L, "Hello\n");

    lua_pcall(L, 1, 0, 0);
    return 0;
}

lua_getglobal函数定义如下:

void lua_getglobal (lua_State *L, const char *name);
Pushes onto the stack the value of the global name.

是把全局变量的值push到堆栈里。在这个程序中,即是把io这个table的值存到堆栈中。

lua_getfield函数定义如下:

void lua_getfield (lua_State *L, int index, const char *k);
Pushes onto the stack the value t[k], where t is the value at the given index. As in Lua, this function may trigger a metamethod for the "index" event

也即把堆栈中指定索引(indextable中的keyk的值push到堆栈。在程序中,即把io.write函数存到堆栈中。

接下来lua_pushstring是把io.write函数的参数push到堆栈,而lua_pcall即执行io.write函数。

执行结果:

[root@Fedora test]# ./hello
Hello

发表评论

邮箱地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.