# autojs-lua
**Repository Path**: yashujs/autojs-lua
## Basic Information
- **Project Name**: autojs-lua
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 2
- **Forks**: 4
- **Created**: 2021-03-09
- **Last Updated**: 2023-10-12
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
## 使用场景
在autojs中使用lua
## 依赖jar
luaJ是一个java实现的lua脚本解释器
```
luaj-jse-3.0.1.jar
```
## 效果展示
## autojs版本
## 原理
1. luaj.jar执行lua
## 知识点
1. 加载jar
2. 导入类
3. 创建globals管理lua全局
4. 执行lua的两种方式
5. 获取lua变量的值
## 代码讲解
1. 加载jar
```js
let dexFilepath = "./luaj-jse-3.0.1.jar";
runtime.loadJar(dexFilepath);
```
2. 导入类
```js
importClass("org.luaj.vm2.lib.jse.JsePlatform");
```
3. 创建Globals对象来管理全局状态
```js
globals = JsePlatform.standardGlobals();
```
4. 执行lua文件
```js
var luaPath = files.path("./luaTest.lua");
globals.loadfile(luaPath).call();
```
5. 获取lua变量的值
```js
c = globals.get("c").toString();
log("c: " + c);
```
6. 另一种运行lua脚本的方式
```js
s = ""; //lua脚本
s += "x=3\r\n";
s += "y=4\r\n";
s += "print ('hello world!')\r\n";
s += "function aa()\r\n";
s += "print ('aaa')\r\n";
s += "end\r\n";
s += "aa()\r\n";
s += "function method1()\r\n";
s += "return x * 2\r\n";
s += "end\r\n";
s += "c=method1(x)\r\n";
chunk = globals.load(s); //加载自己写的脚本
chunk.call(); //执行脚本
c = globals.get("c").toString(); //取得脚本里的变量d的值
log("c: " + c);
```
7. lua代码
```lua
x = 3
y = 4
print("hello world!")
function aa()
print("aaa")
end
aa()
function method1(x)
return x * 2
end
c = method1(x)
print(c)
```
## 完整源码
```js
let dexFilepath = "./luaj-jse-3.0.1.jar";
runtime.loadJar(dexFilepath);
importClass("org.luaj.vm2.lib.jse.JsePlatform");
//创建Globals对象来管理全局状态
globals = JsePlatform.standardGlobals();
var luaPath = files.path("./luaTest.lua");
globals.loadfile(luaPath).call();
c = globals.get("c").toString(); //取得脚本里的变量d的值
log("c: " + c);
// s = ""; //lua脚本
// s += "x=3\r\n";
// s += "y=4\r\n";
// s += "print ('hello world!')\r\n";
// s += "function aa()\r\n";
// s += "print ('aaa')\r\n";
// s += "end\r\n";
// s += "aa()\r\n";
// s += "function method1()\r\n";
// s += "return x * 2\r\n";
// s += "end\r\n";
// s += "c=method1(x)\r\n";
// chunk = globals.load(s); //加载自己写的脚本
// chunk.call(); //执行脚本
// c = globals.get("c").toString(); //取得脚本里的变量d的值
// log("c: " + c);
```
## 微信公众号 AutoJsPro教程

## QQ群
747748653
