Lua实战笔记第3篇 Qt调用lua动态链接库

Qt调用Lua动态链接库

上一篇笔记讲解了如何在VS2017下使用C++调用Lua动态链接库,因笔者平时也喜欢使用Qt,故创作本篇记录Qt是如何调用Lua Dll协助我们工作的

新建Qt工程


 

这是创建好的Qt Console工程

 

将Lua5.1源码目录“src”拷贝至Qt工程目录下,如下图所示

 

在Qt中打开LearnLua.pro文件,将“INCLUDEPATH += ./src”添加到任意位置,至此头文件路径已经配置OK了

 

将lib和dll文件拷贝至生成的exe所在文件目录下
 

在Qt工程main函数中插入如下代码

lua_State *L = lua_open();        
luaopen_base(L);        
luaopen_table(L);        
luaopen_string(L);        
if (luaL_loadfile(L, "Print.lua"))       
{           
//std::string error = "cannot run Lua file: " + filename;            //throw Exception(error.c_str());            //LOGDEBUG(error.c_str());            //cout<<error<<endl;            const char * error = lua_tostring(L, -1);            printf("%s\n 执行脚本文件失败", error);           
return -1;        }        
if (lua_pcall(L, 0, 0, 0))       
{           
const char * error = lua_tostring(L, -1);           
printf("%s\n 执行脚本文件失败", error);           
return -1;        
}

 

新建Print.lua脚本,将其置于exe所在目录的上级目录下

以下代码为Print.lua脚本中的内容

--[[
File name: Print.lua
Description: lua编程Demo1:熟悉lua的基本语法,如变量声明,C语言中if else等语句
                         在lua中的实现
Function List:

Author: Hanc
Version: V0.0
Other:
                1. lua中没有i++这类用法 
                2. while中不能像C一样使用continue功能 
                3. 除了nil和false都为真 
                4. 拼接字符串使用 .. 
                5. C语言中的“&&”“||”“!”在lua中为 and or not 
                6. lua中 != 要用 ~=
                7. 与C/C++不同,lua中的下标是从1开始的
History:
        2019.1.5 创建


]]--
print("hello Lua !!")
--[[
        a = 10  声明全局变量  
        local a = 10    声明局部变量
        lua中尽量使用局部变量,保证垃圾回收及时
        全局变量赋值为“nil”才会交给垃圾回收
--]]
a = 10  

--打印变量的数据类型
print(type(a))
-- 将字符串转换为数字
local c = tonumber("256")
print(c)
--字符串连接使用“..”
local d = "hello baba".."\two shi\n"
--local e = string.len(d)
--print(string.len("we"))

--if else 用法
if(1==1 and 1==2) then
        print("1==1")
else
        print("1 != 1")
end

-- if elseif 用法
if(1==1 and 1==2) then
        print("1==1")
elseif(2==2) then
        print("2 == 2")
end

--break退出,未实现continue
while(nil)      do
print("while")
end

--lua中的do while语句
local i = 100;
repeat
        i = i+1
        print("i = "..i)
until i>110

for var =1,5,1 do
        print("var = "..var)
end

--pairs遍历所有
--ipairs 按照标准数组去访问
local days = {"Sun","Mon","Tus"}
for i,v in ipairs(days) do
        print(i..":"..v)
end

编译运行Qt程序

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明故宫的记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值