硬汉嵌入式论坛

 找回密码
 立即注册
查看: 51|回复: 0
收起左侧

LUA的C源码里面注册函数实现返回两个Table

[复制链接]

1万

主题

7万

回帖

12万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
121230
QQ
发表于 昨天 11:57 | 显示全部楼层 |阅读模式



[Lua] 纯文本查看 复制代码
#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

// 1. 定义C函数,符合 lua_CFunction 原型
static int myfunc_return_two_tables(lua_State *L) {
    // --- 创建并填充第一个Table ---
    lua_newtable(L);                         // 压入第一个新表 (索引 -1)
    lua_pushstring(L, "name");                // 压入键 "name" (索引 -2)
    lua_pushstring(L, "Table One");           // 压入值 "Table One" (索引 -1)
    lua_settable(L, -3);                      // 弹出键和值,设置到第一个表中
                                               // 此时表仍在栈顶 (索引 -1)

    // --- 创建并填充第二个Table ---
    lua_newtable(L);                         // 压入第二个新表 (索引 -1,第一个表现在在 -2)
    lua_pushstring(L, "id");                   // 压入键 "id"
    lua_pushinteger(L, 2);                     // 压入值 2
    lua_settable(L, -3);                      // 设置键值对到第二个表

    // 2. 此时,栈中有两个表:第一个表在索引 -2,第二个表在索引 -1

    // 3. 返回2,表示有两个返回值
    return 2;
}

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

    // 将C函数注册为Lua的全局函数
    lua_register(L, "get_two_tables", myfunc_return_two_tables);

    // 执行Lua代码来测试
    const char *lua_code =
        "local t1, t2 = get_two_tables()\n"
        "print('第一个表:', t1.name)\n"
        "print('第二个表:', t2.id)";
    
    if (luaL_dostring(L, lua_code) != LUA_OK) {
        fprintf(stderr, "错误: %s\n", lua_tostring(L, -1));
    }

    lua_close(L);
    return 0;
}

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|Archiver|手机版|硬汉嵌入式论坛

GMT+8, 2026-3-1 05:58 , Processed in 0.037925 second(s), 24 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2023, Tencent Cloud.

快速回复 返回顶部 返回列表