前言
首先需要明白的是 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_checkstack
to ensure that the stack has extra slots when pushing new elements.
Whenever Lua calls C, it ensures that the stack has at leastLUA_MINSTACK
extra slots.LUA_MINSTACK
is 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 = true
global_Str =