幫一個企業(yè)做網(wǎng)站流程seo線上培訓(xùn)班
文章目錄
- 迭代器
- 主程序
迭代器
-- 定義一個名為 linearSearch 的函數(shù),它接受兩個參數(shù):data(一個數(shù)組)和 target(一個目標(biāo)值)
function linearSearch(data, target) -- 使用 for 循環(huán)遍歷數(shù)組 data,ipairs 是一個迭代器,用于在數(shù)組中遍歷鍵值對 for i, v in ipairs(data) do -- 如果當(dāng)前遍歷到的值 v 等于目標(biāo)值 target if v == target then -- 找到目標(biāo)值,返回其索引 i return i end end -- 如果循環(huán)結(jié)束都沒有找到目標(biāo)值,返回 -1 return -1
end -- 定義一個數(shù)組 data,包含一系列整數(shù)
data = {13, 66, 54, 73, 23, 55, 18}
-- 定義一個變量 target,賦值為 66
target = 66 -- 調(diào)用 linearSearch 函數(shù),并將結(jié)果賦值給變量 res
res = linearSearch(data, target)
-- 打印變量 res 的值
print(res)
Lua 腳本語法的關(guān)鍵點(diǎn):
函數(shù)定義:
function 關(guān)鍵字用于定義函數(shù)。
函數(shù)名后面跟著括號,括號內(nèi)是函數(shù)的參數(shù)列表。
函數(shù)體跟在參數(shù)列表之后,用 end 關(guān)鍵字結(jié)束。
for 循環(huán):
Lua 中的 for 循環(huán)可以配合迭代器使用,例如 ipairs 用于遍歷數(shù)組的索引和值。
for i, v in ipairs(data) do 表示對數(shù)組 data 進(jìn)行遍歷,i 是索引,v 是對應(yīng)的值。
條件語句:
if 語句用于進(jìn)行條件判斷。
如果條件為真(true),則執(zhí)行 then 后面的代碼塊。
可以使用 else 和 elseif 來處理其他情況。
return 語句:
用于從函數(shù)中返回值。
如果函數(shù)中沒有 return 語句,或者 return 后面沒有跟任何值,則默認(rèn)返回 nil。
數(shù)組和變量:
Lua 中的數(shù)組使用花括號 {} 定義,數(shù)組元素之間用逗號分隔。
變量不需要提前聲明,直接使用賦值語句即可創(chuàng)建和初始化。
打印輸出:
使用 print 函數(shù)來打印輸出變量的值或者文本信息。
主程序
function linearSearch(data, target) for i = 1, #data do -- 這是一個for循環(huán),用于遍歷數(shù)組data。#data獲取數(shù)組data的長度。Lua中的數(shù)組索引從1開始,所以循環(huán)變量i從1開始,到數(shù)組的長度結(jié)束。if data[i] == target then return i end end return -1
end -- Main program
do local data = {13, 66, 54, 73, 23, 55, 18} local target = 66 local res = linearSearch(data, target) print(res)
end
Lua 數(shù)組的索引是從1開始的,也就是說它們的索引從1開始計數(shù)。
Lua我們定義了一個全局函數(shù)linearSearch來執(zhí)行搜索。
在Lua中,我們使用一個匿名的do … end塊來包含主程序邏輯。這個塊在腳本運(yùn)行時會被立即執(zhí)行。
在Lua中,局部變量是使用local關(guān)鍵字聲明的。這有助于避免污染全局命名空間。
Lua中的print函數(shù)用于輸出結(jié)果