本节完整覆盖Lua 5.4的所有基础语法结构,包含代码规范、控制结构、运算符等核心概念,特别针对Android平台开发进行优化说明。
Lua的语法元素由标识符、关键字、字符串等基本构件组成。
-- 合法标识符
local _androidVersion = "12"
local screenDPI = 320
local MAX_BUFFER_SIZE = 1024
-- 非法标识符
-- local 2ndPlace -- 数字开头错误
-- local function -- 关键字不能作标识符
and break do else elseif end
false for function goto if in
local nil not or repeat return
then true until while
Lua的变量分全局变量和局部变量,正确使用作用域对Android开发至关重要。
-- 全局变量(应避免)
appVersion = "1.0.0"
-- 局部变量(推荐)
local activity = require "android.app.Activity"
-- 同时声明多个变量
local x, y = 10, 20
local outer = 1
do
local inner = 2
print(outer + inner) -- 输出3
end
-- print(inner) -- 错误:inner不可见
Lua是动态类型语言,但Android开发中需要特别注意类型转换。
print(type("Hello")) -- string
print(type(3.14)) -- number
print(type(true)) -- boolean
print(type(nil)) -- nil
print(type(print)) -- function
print(type({}))) -- table
-- 自动转换
local s = "10" + 2 -- 输出12(字符串转数字)
-- 强制转换
local n = tonumber("123")
local s = tostring(123)
Lua的运算符系统包含算术、关系、逻辑等多种操作符。
print(10 // 3) -- 整除运算 → 3
print(2 ^ 10) -- 幂运算 → 1024
print(10 % 3) -- 取模 → 1
print(3 == 3.0) -- true(值相等)
print(3 ~= 4) -- true(不等于)
print("a" < "b") -- true(字典序)
local enabled = true
local visible = false
print(enabled and visible) -- false
print(enabled or visible) -- true
print(not enabled) -- false
Lua提供完整的流程控制语句,在Android UI开发中尤为重要。
local batteryLevel = 80
if batteryLevel > 90 then
print("高电量")
elseif batteryLevel > 20 then
print("中等电量")
else
print("低电量警告")
end
-- 数值for循环
for i = 1, 5, 2 do -- 从1到5,步长2
print("序号:", i)
end
-- 泛型for循环
local colors = {"red", "green", "blue"}
for index, value in ipairs(colors) do
print(index, value)
end
函数是Lua的核心特性,Android开发中常用作事件回调。
-- 全局函数
function showToast(text)
android.showToast(text)
end
-- 局部函数
local function calculate(a, b)
return a + b, a - b
end
local function getScreenInfo()
return 1080, 1920, 420 -- 宽度,高度,DPI
end
local w, h = getScreenInfo()
Android开发中字符串操作频繁,需掌握高效处理方法。
local path1 = "/sdcard/data.txt" -- 单引号/双引号
local path2 = [[
/sdcard/
multi-line
path.txt
]]
local s = "Lua on Android"
print(string.upper(s)) -- "LUA ON ANDROID"
print(string.sub(s, 5)) -- "on Android"
print(string.find(s, "Android")) -- 返回开始位置
table.concat