Lua Table 操作


Lua中table類似與C#種的字典,其實就是一個key-value鍵值對數據結構.來學習下table基本操作

Table的創建

myTable = {}                                        --表名后面使用{}賦值,表示一個空的表
myTable = {name="盤子臉",age=18,isMan=true}          --創建時候就添加鍵-值
myTable = {10,20,30,"plateface"}                    --創建數字下標值的table,默認是從1開始

Table的賦值

myTable[3] = 34                   --當鍵是一個數字的時候的賦值方式
myTable["name"] = "盤子臉"         --當鍵是一個字符串的賦值方式
myTable.name = "plateface"        --跟myTable["name"]訪問的是同一個value, print(myTable.name) 輸出plateface

Table的訪問

myTable[3]          --當鍵是數字的時候,只有一種訪問方式
myTable.name        --當鍵是字符串的時候有兩種訪問方式
myTable["name"]

Table的遍歷

myTable = {10,20,30,40}
for index=1,table.getn(myTable) do
    print(myTable[index])
end
    
for index,value in ipairs(myTable) do
    print(index,value)
end

表相關的函數:

table.conccat 把表中所有數據連成一個字符串
table.insert 在表中2的位置插入一個
table.remove 移除指定位置的數據
table.sort 排序

通過表來實現面向對象(一)

Enemy = {}
local this = Enemy
    
--定義屬性
Enemy.hp = 100
Enemy.speed = 12.3

--定義方法
Enemy.Move = function()
    print("敵人在移動")
end

function Enemy.Attack()
    print(this.hp," 敵人的HP")
    this.Move()
end

--調用攻擊方法
Enemy.Attack()

通過表來實現面向對象(二)

Apple = {}

--使用:給table添加方法
function Apple:new()
    Apple.str = "蘋果的價格是6元"
    return Apple;
end

function Apple:toString()
    print(Apple.str)
end

local a = Apple:new()
print(a.toString())


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM