這裏的問題是你對如何使用默認的lua值類型感到困惑。表和用戶數據是您將設置/獲取屬性的唯一兩種數據類型。我會分解你的代碼,所以也許它會幫助你理解如何使用表來做你想做的事...
你開始創建一個名爲空表的表。該表中沒有任何值或屬性可供您參考。
local names = {}
在你的循環,你拉出一個字符從string「STR」一個字符時,它在索引分配到名稱指向計數(應該是從1開始,順便說一句..因爲字符串
盧阿的表格索引是基於1的,而不是以0爲基礎的)。所以在第二圈你基本上這樣做:
names[1] = 'H'
(第一循環計數器爲0,所以string.sub(STR,0,0)返回一個空字符串)之後
直接,你一次做了幾個步驟,這就是你感到困惑的地方。打破它應該爲你清除它。
local a_char = names[count] -- get the string value in index 'count'
a_char.id = count -- try to set property id on that string value
names[count] = a_char -- assign this value to index 'count' in table names
上面的代碼在邏輯上等同於名稱[count] .id = count。你正在試圖創建/設置一個字符串值爲'id'的屬性。字符串沒有這個屬性,你不能創建它,這就是解釋器咆哮你的原因。
如果要將邏輯信息一起存儲在lua表中,則規範將使用嵌套表。這聽起來像你想要基本上將每個字符存儲在字符串'str'中以及它在表'名稱'中的位置。這將是你如何做到這一點:
local names = {}
str = "Hello World"
for count = 1, #str do
local cha, idx = string.sub(str, count, count), count
-- below creates an anonymous table with two properties (character, and id) and
-- adds it to the end of table 'names'.
table.insert(names, {character = cha, id = idx})
-- or
-- names[count] = {character = cha, id = idx}
end
進行邏輯分組的信息,你想要的方式,並且數據看起來大致是這樣的表格:
{ {character = 'H', id = 1}, {character = 'e', id = 2} ... }
,如果你想要的從表中的第一個項目編號,你會參考它像你所做的上述:
local first_id = names[1].id -- access property id from table in first index in table names
哇!那真的爲我清理了一些東西。感謝您的詳細回覆,我對LUA很陌生。這正是我想說的和尋找的東西。問題:要訪問這個,我需要在for循環中使用「in pair」函數嗎?非常感謝。 – rpcabrera 2012-04-25 02:16:09
是的,對()和ipairs()是枚舉表的兩個最常用的函數...您也可以使用next()。隨時標記我的答覆作爲答案,如果它回答了你所有的關注:) – 2012-04-25 02:24:06
再次感謝VBRonPaulFan的詳細答覆,像我這樣的新手可以理解。 – rpcabrera 2012-04-25 03:37:24