gpt4 book ai didi

lua - Lua如何处理栈?

转载 作者:行者123 更新时间:2023-12-02 22:33:12 25 4
gpt4 key购买 nike

我正在尝试 Lua,想知道 lua_State 是如何工作的
代码和结果:

状态.c

#include <stdio.h>
#include "lua/src/lua.h"
#include "lua/src/lauxlib.h"
static void stackDump(lua_State *L){
int i;
int top = lua_gettop(L);
for(i = 1; i<= top; i++) {
int t = lua_type(L, i);
switch(t){
case LUA_TSTRING:
printf("'%s'", lua_tostring(L, i));
break;
case LUA_TBOOLEAN:
printf(lua_toboolean(L, i) ?"true":"false");
break;
case LUA_TNUMBER:
printf("%g", lua_tonumber(L, i));
break;
default:
printf("%s", lua_typename(L, t));
break;
}
printf(" ");
}
printf("\n");
}

static int divide(struct lua_State *L){

double a = lua_tonumber(L, 1);
double b = lua_tonumber(L, 2);
printf("%p\n", L);

stackDump(L);

int quot = (int)a / (int)b;
int rem = (int)a % (int)b;

lua_pushnumber(L, quot);
lua_pushnumber(L, rem);

stackDump(L);
printf("---end div---\n");

return 2;
}

int main(void){
struct lua_State *L = lua_open();
lua_pushboolean(L, 1);
lua_pushnumber(L, 10);
lua_pushnil(L);
lua_pushstring(L, "hello");

printf("%p\n", L);

stackDump(L);

lua_register(L, "div", divide);
luaL_dofile(L, "div.lua");

stackDump(L);
lua_close(L);
return 0;
}

div.lua
本地 c = div(20, 10)

0x100c009e0
true 10 nil 'hello'
---start div---
0x100c009e0
20 10
20 10 2 0
---end div---
true 10 nil 'hello'

我看到 divide 中的 lua_Statemain 中的相同,但它们在堆栈中的数据不同,这是如何完成的?

我知道理解这个的最好方法是阅读 Lua 的源代码,也许你能告诉我在哪里可以找到正确的地方。

最佳答案

将 lua_State 视为包含 Lua 堆栈,以及分隔堆栈当前可见部分的索引。当你调用一个 Lua 函数时,看起来你有一个新的堆栈,但实际上只有索引发生了变化。这是简化版。

lua_Statelstate.h 中定义。我已经为您提取了相关部分。 stack 是包含所有内容的大 Lua 堆栈的开始。 base 是当前函数堆栈的开始。这就是您的函数在执行时所看到的“堆栈”。

struct lua_State {
/* ... */
StkId top; /* first free slot in the stack */
StkId base; /* base of current function */
/* ... */
StkId stack_last; /* last free slot in the stack */
StkId stack; /* stack base */
/* ... */
};

Programming in Lua, 2nd Edition 在第 30 章中讨论了 Lua 状态:线程和状态。你会在那里找到一些很好的信息。例如,lua_State 不仅表示一个 Lua 状态,而且表示该状态内的一个线程。此外,所有线程都有自己的堆栈。

关于lua - Lua如何处理栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11877913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com