基本语法

       本节完整覆盖Lua 5.4的所有基础语法结构,包含代码规范、控制结构、运算符等核心概念,特别针对Android平台开发进行优化说明。

1. 词法约定

       Lua的语法元素由标识符、关键字、字符串等基本构件组成。

1.1 标识符规则

-- 合法标识符
local _androidVersion = "12"
local screenDPI = 320
local MAX_BUFFER_SIZE = 1024

-- 非法标识符
-- local 2ndPlace  -- 数字开头错误
-- local function  -- 关键字不能作标识符

1.2 关键字列表

and       break     do        else      elseif    end
false     for       function  goto      if        in
local     nil       not       or        repeat    return
then      true      until     while

2. 变量与作用域

       Lua的变量分全局变量和局部变量,正确使用作用域对Android开发至关重要。

2.1 变量声明

-- 全局变量(应避免)
appVersion = "1.0.0"

-- 局部变量(推荐)
local activity = require "android.app.Activity"

-- 同时声明多个变量
local x, y = 10, 20

2.2 作用域链

local outer = 1

do
    local inner = 2
    print(outer + inner)  -- 输出3
end

-- print(inner)  -- 错误:inner不可见

3. 数据类型基础

       Lua是动态类型语言,但Android开发中需要特别注意类型转换。

3.1 类型检测

print(type("Hello"))   -- string
print(type(3.14))     -- number
print(type(true))     -- boolean
print(type(nil))      -- nil
print(type(print))    -- function
print(type({})))      -- table

3.2 类型转换

-- 自动转换
local s = "10" + 2  -- 输出12(字符串转数字)

-- 强制转换
local n = tonumber("123")
local s = tostring(123)

4. 表达式与运算符

       Lua的运算符系统包含算术、关系、逻辑等多种操作符。

4.1 算术运算符

print(10 // 3)   -- 整除运算 → 3
print(2 ^ 10)   -- 幂运算 → 1024
print(10 % 3)   -- 取模 → 1

4.2 关系运算符

print(3 == 3.0)   -- true(值相等)
print(3 ~= 4)    -- true(不等于)
print("a" < "b")  -- true(字典序)

4.3 逻辑运算符

local enabled = true
local visible = false

print(enabled and visible)  -- false
print(enabled or visible)   -- true
print(not enabled)          -- false

5. 控制结构

       Lua提供完整的流程控制语句,在Android UI开发中尤为重要。

5.1 条件语句

local batteryLevel = 80

if batteryLevel > 90 then
    print("高电量")
elseif batteryLevel > 20 then
    print("中等电量")
else
    print("低电量警告")
end

5.2 循环结构

-- 数值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

6. 函数定义

       函数是Lua的核心特性,Android开发中常用作事件回调。

6.1 基础定义

-- 全局函数
function showToast(text)
    android.showToast(text)
end

-- 局部函数
local function calculate(a, b)
    return a + b, a - b
end

6.2 多返回值

local function getScreenInfo()
    return 1080, 1920, 420  -- 宽度,高度,DPI
end

local w, h = getScreenInfo()

7. 字符串处理

       Android开发中字符串操作频繁,需掌握高效处理方法。

7.1 字符串声明

local path1 = "/sdcard/data.txt"  -- 单引号/双引号
local path2 = [[
/sdcard/
multi-line
path.txt
]]

7.2 字符串操作

local s = "Lua on Android"

print(string.upper(s))   -- "LUA ON ANDROID"
print(string.sub(s, 5))  -- "on Android"
print(string.find(s, "Android"))  -- 返回开始位置

Android开发特别提示