前言
首先需要明白的是 C与 Lua 的虚拟堆栈。
引用 Lua 官方的解释:The Stack
Lua uses a virtual stack to pass values to and from C. Each element in this stack represents a Lua value (nil, number, string, etc.).
Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active. This stack initially contains any arguments to the C function and it is where the C function pushes its results to be returned to the caller (see lua_CFunction).
For convenience, most query operations in the API do not follow a strict stack discipline. Instead, they can refer to any element in the stack by using an index: A positive index represents an absolute stack position (starting at 1); a negative index represents an offset relative to the top of the stack. More specifically, if the stack has n elements, then index 1 represents the first element (that is, the element that was pushed onto the stack first) and index n represents the last element; index -1 also represents the last element (that is, the element at the top) and index -n represents the first element.Stack Size
When you interact with the Lua API, you are responsible for ensuring consistency. In particular, you are responsible for controlling stack overflow. You can use the function
lua_checkstackto ensure that the stack has extra slots when pushing new elements.
Whenever Lua calls C, it ensures that the stack has at leastLUA_MINSTACKextra slots.LUA_MINSTACKis defined as 20, so that usually you do not have to worry about stack space unless your code has loops pushing elements onto the stack.
When you call a Lua function without a fixed number of results (seelua_call), Lua ensures that the stack has enough size for all results, but it does not ensure any extra space. So, before pushing anything in the stack after such a call you should uselua_checkstack.
C语言操作 Lua 全局变量(基本类型)
获取 Lua 全局变量
C语言读取Lua中的全局变量需要两步:
- 将全局变量从
Lua Space压入虚拟堆栈- 从堆栈将全局变量读取到
C Space中在
Lua和C的交互中,Lua无法看到和操作虚拟堆栈,仅在C语言中有操作堆栈的权利。
Lua代码:
global_Num = 1789;
global_bool =

本文介绍了如何在C语言中与Lua进行交互,包括获取和设置Lua全局变量、调用Lua函数以及操作Lua Table。通过理解Lua的虚拟堆栈工作原理,确保了C代码能正确地与Lua交互。
最低0.47元/天 解锁文章
528

被折叠的 条评论
为什么被折叠?



