如何编写一个简单的TypeScriptToLua lua 模块定义包
以下主要说明下简单的编写,对于复杂的后续会介绍(以为lua 语言的特殊性,部分需要依赖其他类型)
一个案例
比如我们有一个lua 模块,包装一个平台认证服务(为了方便openresty 使用的,基于lua+c 开发的)
我们为了方便大家开发方便,提供了基于TypeScriptToLua 的定义包,这样前端同学也就可以方便的编写lua 模块了
- 参考lua接口定义
假如我们约定我们的模块名称为platformlogin
local function loginv1(name,password)
--- code
end
local function logoutv1()
--- code
end
return {
login = loginv1,
logout = logoutv1
}
参考ts 包开发
- package.json
{
"name": "@dalongrong/platform-login",
"version": "1.0.1",
"types": "platform-login.d.ts",
"files": [
"*.d.ts"
],
"license": "MIT",
"scripts": {
"p": "yarn publish"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.com"
}
}
platform-login.d.ts
基于以上的约定我们使用了module,实际上也是可以直接使用namespace的(而且很多时候直接使用namespace 是不错的选择)
/** @noSelfInFile */
declare module "platformlogin" {
type opResult = 0 |1
function login(name:string,password):string
function logout():opResult
}
ts 项目引用开发的模块定义
- package.json
{
"name": "mylogin-ts",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"build": "tstl",
"dev": "tstl --watch"
},
"devDependencies": {
"@dalongrong/platform-login": "^1.0.2",
"typescript": "^4.6.3",
"typescript-to-lua": "^1.4.3"
}
}
- tsconfig.json
{
"tstl": {
"luaTarget": "JIT",
"noHeader":true,
"noImplicitSelf":true,
"buildMode": "library",
"noResolvePaths":["platformlogin"] // 忽略引用包的解析,因为是原生lua 模块
},
"compilerOptions": {
"types": ["@dalongrong/platform-login"], // 类型定义
"target": "es2016",
"outDir": "dist",
"module": "commonjs", /* Specify what module code is generated. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
- 代码集成
import * as demo from "platformlogin"
let token = demo.login("name","password")
console.log(token)
- 使用效果
说明
以上是一个简单的开发说明,比较简单,但是可以参考,有助于基于ts开发高效的lua 模块
参考资料
https://github.com/TypeScriptToLua/lua-types
https://github.com/andrei-markeev/openresty-lua-type
https://typescripttolua.github.io/
https://typescripttolua.github.io/docs/advanced/writing-declarations
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2021-04-22 cube.js 调度&&查询队参考参数
2021-04-22 cube.js 自定义首页显示信息
2020-04-22 How We Spotted and Fixed a Performance Degradation in Our Python Code
2020-04-22 nodejs 基础镜像的一个参考
2020-04-22 几款不错的基于web 的sql编辑器
2019-04-22 python 集成cython 简单测试
2019-04-22 click python cli 开发包