惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

aimingoo的专栏
aimingoo的专栏
Security Archives - TechRepublic
Security Archives - TechRepublic
NISL@THU
NISL@THU
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
A
Arctic Wolf
C
Cyber Attacks, Cyber Crime and Cyber Security
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
The Blog of Author Tim Ferriss
Simon Willison's Weblog
Simon Willison's Weblog
V
Visual Studio Blog
T
Tenable Blog
J
Java Code Geeks
C
CERT Recently Published Vulnerability Notes
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 叶小钗
人人都是产品经理
人人都是产品经理
U
Unit 42
宝玉的分享
宝玉的分享
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
Last Week in AI
Last Week in AI
Forbes - Security
Forbes - Security
I
Intezer
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
Scott Helme
Scott Helme
月光博客
月光博客
Google Online Security Blog
Google Online Security Blog
T
Tailwind CSS Blog
爱范儿
爱范儿
Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LangChain Blog
S
Securelist
Spread Privacy
Spread Privacy
D
Darknet – Hacking Tools, Hacker News & Cyber Security
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Proofpoint News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
Hugging Face - Blog
Hugging Face - Blog
S
Security Affairs
S
SegmentFault 最新的问题
L
Lohrmann on Cybersecurity
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tor Project blog
博客园 - 聂微东
H
Heimdal Security Blog
B
Blog
Attack and Defense Labs
Attack and Defense Labs

浮生笔记

时机的重要性 回答dayu博客的几个问题 学会做选择 我理想的城市 如何选择一个适合的城市 马来西亚游记 回首2023,展望2024 从ChatGPT聊起 菲律宾旅游攻略笔记 深圳游记 香港游记 怎样赚钱----我理解的商业模式 用户界面与跨平台 使用telnet通过IMAP协议读取QQ邮箱 信息成本-----从ChatGPT到情报学 买断制到订阅制----兼谈消费频次 我眼中的CSDN 迁移博客内容到静态博客 Hugo使用Jane主题支持搜索实现 从放逐之城看经济学 不同产业的分析 回首2021,展望2022 游戏中的经济学 Windows获取网络地址、子网掩码等 -fsanitize=address 参数作用 C++ 编译器支持标准判断 C++ 编译器支持标准判断 VS Code的golang开发配置 之 代码提示 二叉树遍历的非递归算法的实现 我的Chrome插件 golang 获取get参数 关于写代码的几个看法 golang编程之我见 Linux 网络编程之 Select 构建之法读书笔记 (1) 友情链接 Effective Morden C++ 读书笔记(3) 二进制协议 vs 文本协议 从重构到重写 asio制作使用ssl通信的证书 gdb 7.11 Linux 获取网卡信息 《构建之法》读后感 由买冰箱想到的 2014年年终总结 聊聊我对写好程序的认识 编程技巧之表格驱动编程 经验搜索排名---google已经做过类似的了(我想多了) 有关编程语言的认识
C语言和Lua的相互调用示例代码
DennisThink · 2022-08-17 · via 浮生笔记

本代码参考博客: https://lucasklassmann.com/blog/2019-02-02-how-to-embeddeding-lua-in-c/

/**
 * @file luaLearn.c
 * @brief C and Lua call Learn Demo
 * @version 0.1
 * @date 2022-08-19
 * 
 * @copyright Copyright (c) 2022
 * 
 */

//参考文档
//https://lucasklassmann.com/blog/2019-02-02-how-to-embeddeding-lua-in-c/

#include <stdio.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>


//基本的Lua和C交互的函数
int BasicLuaFunction()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    // Work with lua API
    lua_close(L);
    return 0;
}


//无参数调用Lua
int CallLuaFunctionWithOutArguments()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    char* pLua = "print('this is lua')";
    // Work with lua API
     // Here we load the string and use lua_pcall for run the code
    int nLoadRet = luaL_loadstring(L, pLua);
    if (nLoadRet == LUA_OK) {
        if (lua_pcall(L, 0, 0, 0) == LUA_OK) {
            // If it was executed successfuly we 
            // remove the code from the stack
            lua_pop(L, lua_gettop(L));
        }
    }
    lua_close(L);
    return 0;
}

//Set Lua variable value in C function
int SetLuaVariableValueInCfunction()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);

    lua_pushinteger(L, 42);
    lua_setglobal(L, "answer");

    char* code = "print(answer)";

    if (luaL_dostring(L, code) == LUA_OK) {
        lua_pop(L, lua_gettop(L));
    }

    lua_close(L);
    return 0;
}

// Define our function, we have to follow the protocol of lua_CFunction that is 
// typedef int (*lua_CFunction) (lua_State *L);
// When this function is called by Lua, the stack contains the arguments needed, 
// what we need to do check if the arguments have the type that we expect.
int multiplication(lua_State* L) {

    // Check if the first argument is integer and return the value
    int a = luaL_checkinteger(L, 1);

    // Check if the second argument is integer and return the value
    int b = luaL_checkinteger(L, 2);

    // multiply and store the result inside a type lua_Integer
    lua_Integer c = a * b;

    // Here we prepare the values to be returned.
    // First we push the values we want to return onto the stack in direct order.
    // Second, we must return the number of values pushed onto the stack.

    // Pushing the result onto the stack to be returned
    lua_pushinteger(L, c);

    return 1; // The number of returned values
}

//从Lua中调用C语言编写的函数,带参数
int CallCfunctionFromLua()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);

    // Push the pointer to function
    lua_pushcfunction(L, multiplication);

    // Get the value on top of the stack
    // and set as a global, in this case is the function
    lua_setglobal(L, "mul");

    // we can use the function `mul` inside the Lua code
    char* code = "print(mul(7, 8))";

    if (luaL_dostring(L, code) == LUA_OK) {
        lua_pop(L, lua_gettop(L));
    }

    lua_close(L);
    return 0;

}


//func5.lua--> print("hello,word from lua")
//Call Lua function from lua file
int CallLuaFunctionFromLuaFile()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_dofile(L, "luafunction.lua") == LUA_OK) {
        lua_pop(L, lua_gettop(L));
    }

    lua_close(L);
    return 0;

}

//GetVariableValueFromLua.lua --->message = 'This message is stored inside lua code'
//从Lua文件中获取Lua变量的值
int GetVariableValueFromLuaFile()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_dofile(L, "GetVariableValueFromLua.lua") == LUA_OK) {
        lua_pop(L, lua_gettop(L));
    }

    lua_getglobal(L, "message");

    if (lua_isstring(L, -1)) {
        const char * message = lua_tostring(L, -1);
        lua_pop(L, 1);
        printf("Message from lua: %s\n", message);
    }

    lua_close(L);
    return 0;
}


//luafunc.lua --->
/*
function my_function()
    print("Hello from Function in Lua")
end
*/
int CallFunctionDefinedInLuaFile()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_dofile(L, "LuaDefinedFunction.lua") == LUA_OK) {
        lua_pop(L, lua_gettop(L));
    }

    lua_getglobal(L, "my_function");
    if (lua_isfunction(L, -1)) {
        if (lua_pcall(L, 0, 1, 0) == LUA_OK) {
            lua_pop(L, lua_gettop(L));
        }
    }

    lua_close(L);
    return 0;
}


//Calling a Lua function in C with arguments and return value
//luaFunctionWithArguments.lua
/*
function my_function(a, b)
    return a * b
end
*/

int CallFunctionDefinedInLuaFileWithArgmentsAndReturnValue()
{
     lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_dofile(L, "luaFunctionWithArguments.lua") == LUA_OK) {
        lua_pop(L, lua_gettop(L));
    }

    // Put the function to be called onto the stack
    lua_getglobal(L, "my_function");
    lua_pushinteger(L, 3);  // first argument
    lua_pushinteger(L, 4);  // second argument

    // Execute my_function with 2 arguments and 1 return value
    if (lua_pcall(L, 2, 1, 0) == LUA_OK) {

        // Check if the return is an integer
        if (lua_isinteger(L, -1)) {

            // Convert the return value to integer
            int result = lua_tointeger(L, -1);

            // Pop the return value
            lua_pop(L, 1);
            printf("Result: %d\n", result);
        }
        // Remove the function from the stack
        lua_pop(L, lua_gettop(L));
    }

    lua_close(L);
    return 0;
}


int CallLuaFunctionWithErrorHandling()
{

    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    char * code = "print(return)"; // intentional error

    if (luaL_dostring(L, code) != LUA_OK) {
        puts(lua_tostring(L, lua_gettop(L)));
        lua_pop(L, lua_gettop(L));
    }

    lua_close(L);
    return 0;
}
int main(int argc, char** argv) {

    printf("This is c main function\n");
    BasicLuaFunction();
    CallLuaFunctionWithOutArguments();
    CallCfunctionFromLua();
    CallLuaFunctionFromLuaFile();
    CallFunctionDefinedInLuaFile();
    CallFunctionDefinedInLuaFileWithArgmentsAndReturnValue();
    CallLuaFunctionWithErrorHandling();
    SetLuaVariableValueInCfunction();
    GetVariableValueFromLuaFile();
    return 0;
}
/*int main(int argc, char* argv[])
{
	printf("This is c main function\n");
	return 0;
}*/

文章作者 DennisThink

上次更新 2022-08-17

许可协议 CC BY-NC-ND 4.0