当前位置:网站首页>Interaction between C language and Lua (practice 2)
Interaction between C language and Lua (practice 2)
2022-06-09 10:33:00 【ufgnix0802】
C Language and Lua Interaction ( Practice two )
How to build the environment can be referred to :https://blog.csdn.net/qq135595696/article/details/125137333?spm=1001.2014.3001.5501
C Language call Lua function
stay lua.c Medium main Function , Delete existing code , Change to the following code :
void test2(lua_State* L)
{
// Get how many elements already exist in the stack
int top = lua_gettop(L);
printf("top:[%d]\n", top);
// Name the global variable func2 Function stack of , Returns the type of the value
int type = lua_getglobal(L, "func2");
//printf("type:%d\n", type);
// Call the function in protected mode , After calling, you must restore Lua Stack , For example, after calling a function, it returns two values , You have to use lua_pop(L,2) take Lua Stack empty .
// When the function is called , All the parameters and the function itself will be out of the stack , The return value of the function is pushed onto the stack .
//int lua_pcall(lua_State* L,int nergs,int nresults,int msgh);
//L:Lua virtual machine
//nergs: The number of formal parameters pushed into the stack
//nresults: Number of returned parameters
//msgh If 0, The error message returned to the top of the stack is exactly the same as the original message .
// Press in a string
lua_pushstring(L, "Hello Wolrd");
// Press in an integer
lua_pushnumber(L, 1000);
// Push in a boolean type
lua_pushboolean(L, 666);
// Call function
if (0 != lua_pcall(L, 3, 2, 0))
printf("error[%s]\n", lua_tostring(L, -1));
printf("%d=====\n", lua_gettop(L));
const char* str = lua_tostring(L, -2);// Get the returned value
int value = lua_tonumber(L, -1);//-1 Represents the top of the stack (-2 Under the top of the stack ),1 Indicates the bottom of the stack
printf(" To the top of the stack :%d Under the top of the stack :%s\n", value, str);
// Clear the return value , Stack balancing
lua_pop(L, lua_gettop(L) - top);// perhaps , Since you already know that calling this function returns two parameters , You can use it directly lua_pop(L, 2);
top = lua_gettop(L);
printf("top:[%d]\n", top);
printf("---- Demarcation line ---\n");
}
int main(int argc, char** argv) {
// Create a virtual machine
lua_State* L = luaL_newstate();
// Load some common system libraries
luaL_openlibs(L);
if (luaL_dofile(L, "main.lua"))
printf("%s\n", lua_tostring(L, -1));
test2(L);
test2(L);
test2(L);
test2(L);
// Shut down the virtual machine
lua_close(L);
return 0;
}
among ,main.lua The code for is as follows ( Pay attention to the need to follow lua.c Files are placed in the same file path ):
-- main.lua
function func2(a,b,c)
print(a,b,c)
return "hello world",123
end
The operation results are as follows :

C Set a language table Data to Lua
Example 1
stay lua.c Medium main Function , Delete existing code , Change to the following code :
int main(int argc, char** argv) {
// Create a virtual machine
lua_State* L = luaL_newstate();
// Load some common system libraries
luaL_openlibs(L);
lua_newtable(L);// Create a table type
lua_pushstring(L, "dlw");// Now there are two elements in the stack ,table and “dlw”
int top = lua_gettop(L);
printf("top:%d\n", top);
lua_pushstring(L, "111");// Now there are three elements in the stack ,“111” Stack top ,“dlw” Under the top of the stack
top = lua_gettop(L);
printf("top:%d\n", top);
lua_settable(L, -3);// In the stack key and value Set to table In the middle , by {"dlw" = "111"}, At the moment, there is only table
top = lua_gettop(L);
printf("top:%d\n", top);
lua_setglobal(L, "tab"); // Will now create table Name it tab Global variables , Now the stack is empty
top = lua_gettop(L);
printf("top:%d\n", top);
lua_newtable(L);
lua_pushstring(L, "dlw");// Now there are two elements in the stack
top = lua_gettop(L);
printf("top:%d\n", top);
lua_setfield(L, 1, "name");// perhaps lua_setfield(L, -2, "name"); Now there is an element in the stack , Means to insert... Under the top of the stack “name”, here {"name"="dlw"}, Press it in again table in
top = lua_gettop(L);
printf("top:%d\n", top);
lua_setglobal(L, "tab1");
// load lua Document and execute The name is main.lua
if (luaL_dofile(L, "main.lua"))
{
// stay lua in -1 Represents the top of the stack If something goes wrong The error result will be placed at the top of the stack
printf("%s\n", lua_tostring(L, -1));
}
// Shut down the virtual machine
lua_close(L);
return 0;
}
among ,main.lua The code for is as follows ( Pay attention to the need to follow lua.c Files are placed in the same file path ):
-- main.lua
print(tab.dlw)
print(tab1.name)
The operation results are as follows :

Example 2
int main(int argc, char** argv) {
// Create a virtual machine
lua_State* L = luaL_newstate();
// Load some common system libraries
luaL_openlibs(L);
// Create a table
lua_newtable(L);
lua_pushstring(L, "dlw");
// Make an equivalent of table["name"] = "dlw" The operation of , here "name" Is the value at the given index , and "dlw" Is the value at the top of the stack
lua_setfield(L, 1, "name");
lua_pushstring(L, "Hello World");
lua_rawseti(L, -2, 1);// Associate the element at the specified index position with the top of the stack element , namely table[1] = "Hello World";
lua_setglobal(L, "tab");// Will now create table Name it tab Global variables
// load lua Document and execute The name is main.lua
if (luaL_dofile(L, "main.lua"))
{
// stay lua in -1 Represents the top of the stack If something goes wrong The error result will be placed at the top of the stack
printf("%s\n", lua_tostring(L, -1));
}
// Shut down the virtual machine
lua_close(L);
return 0;
}
-- main.lua
print(tab.name)
print(tab[1])
The operation results are as follows :

C Language call Lua Set up table type
stay lua.c Medium main Function , Delete existing code , Change to the following code :
int main(int argc, char** argv) {
// Create a virtual machine
lua_State* L = luaL_newstate();
// Load some common system libraries
luaL_openlibs(L);
// load lua Document and execute The name is main.lua
if (luaL_dofile(L, "main.lua"))
{
// stay lua in -1 Represents the top of the stack If something goes wrong The error result will be placed at the top of the stack
printf("%s\n", lua_tostring(L, -1));
}
int top = lua_gettop(L);
printf("%d\n", top);
lua_getglobal(L, "tab");// Get global variables tab
top = lua_gettop(L);
printf("%d\n", top);
// Data type checking , Check whether it is a table .
luaL_checktype(L, -1, LUA_TTABLE);// At this point, the stack is still an element
top = lua_gettop(L);
//printf("%d\n", top);
// take key Pressure into the stack , Function will return value Value to the top of the stack
if (LUA_TSTRING == lua_getfield(L, -1, "name"))// Determine if it's a string
{
top = lua_gettop(L);
printf("%d\n", top);
const char* str = luaL_checkstring(L, -1);
printf("%s\n", str);
}
lua_pop(L, 1);// Balance the stack
// take key Pressure into the stack , Function will return value Value to the top of the stack
if (LUA_TSTRING == lua_geti(L, -1, 2))
{
const char* str = luaL_checkstring(L, -1);
printf("%s\n", str);
}
lua_pop(L, 1);// Balance the stack
lua_pop(L, 1);// Balance the stack , This is the lua_getglobal(L, "tab") Balance
// Shut down the virtual machine
lua_close(L);
return 0;
}
among ,main.lua The code for is as follows ( Pay attention to the need to follow lua.c Files are placed in the same file path ):
-- main.lua
tab = {
name = 'dlw'}
tab[1] = 123321
tab[2] = '123321aa'
The operation results are as follows :

边栏推荐
- 长大后的我们为何贪恋年少?
- Test development engineers who don't work overtime are not good programmers? It may not be a stupid bird, but it always flies first
- 1340. 跳跃游戏 V-动态规划加dfs
- Other permission verification methods
- Authentication successful processor
- Terrain learning summary (6) -- terrain practice based on Alibaba cloud platform
- Machine learning housing rental price forecasting: exploratory data analysis + Feature Engineering + modeling + reporting
- 面试题 01.06. 字符串压缩
- 自定义失败处理
- 【图像增强】基于稀疏表示和正则化实现图像增强附matlab代码
猜你喜欢
![[model deployment and business implementation] model transformation of AI framework deployment scheme](/img/ea/8ca6bc6ae16ba1f90f6a5a38be184d.jpg)
[model deployment and business implementation] model transformation of AI framework deployment scheme

15 must know MySQL index failure scenarios, stop stepping on the pit!

“当你不再是程序员,很多事会脱离掌控”—— 对话全球最大独立开源公司SUSE CTO...

UnsupportedOperationException异常解决

IBM announced its withdrawal from Russia after a loss of $300million!
![[genius_platform software platform development] lecture 37: network card hybrid mode and raw socket](/img/bf/880fbf4122b66723b6e17c6d9d97c9.jpg)
[genius_platform software platform development] lecture 37: network card hybrid mode and raw socket

AppScan检查到的一些中高危漏洞解决方案

Security monitoring video easycvr video access interface adds the close button of a single video
![[genius_platform software platform development] lesson 36: definition of maximum value macro of built-in data type](/img/f1/ca57934507bb0758b8bb0a52606a10.jpg)
[genius_platform software platform development] lesson 36: definition of maximum value macro of built-in data type

【模型部署与业务落地】AI 框架部署方案之模型转换
随机推荐
leetcode. 36 --- effective Sudoku
【模型部署与业务落地】AI 框架部署方案之模型转换
认证成功处理器
How to manage cloud computing platform users?
损失 3 亿美元后,IBM 宣布退出俄罗斯!
349. 两个数组的交集
不加班的测试开发工程师不是好程序员?可能不是一只笨鸟,但一直在先飞......
UnsupportedOperationException异常解决
Authentication successful processor
华泰证券是安全的吗
【PHP】代码复用特殊类Trait的简要说明和相关举例
[optics] double slit interference with GUI Based on MATLAB simulation light
Kubernetes第七篇:Pod進階、Controller進階、Resource和Dashboard
Unemployment wave? Yuancosmos opens up new employment opportunities
1331. array sequence number conversion - quick sort plus binary search
Kubernetes第七篇:Pod进阶、Controller进阶、Resource和Dashboard
Getting started with cloud based LDAP (Part 1)
Interview question 10.03 Search rotation array
【LeetCode】【牛客】二叉树刷题
1331. 数组序号转换-快速排序加二分查找