Lua与C\C++语言的交互-C调用Lua

本文介绍了如何在C语言中与Lua进行交互,包括获取和设置Lua全局变量、调用Lua函数以及操作Lua Table。通过理解Lua的虚拟堆栈工作原理,确保了C代码能正确地与Lua交互。
摘要由CSDN通过智能技术生成

前言

首先需要明白的是 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 least LUA_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 (see lua_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 use lua_checkstack.

C语言操作 Lua 全局变量(基本类型)

获取 Lua 全局变量

C语言读取Lua中的全局变量需要两步:

  • 将全局变量从Lua Space压入虚拟堆栈
  • 从堆栈将全局变量读取到 C Space

LuaC的交互中,Lua无法看到和操作虚拟堆栈,仅在C语言中有操作堆栈的权利。


Lua 代码:

global_Num = 1789;
global_bool = true
global_Str = 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值