通常,我用兩個變量來的東西輸出存儲這樣的:商店的Lua string.match輸出到陣列
a = {'alarm boy car dentist','alarm car dentist elephant','alarm dentist elephant fabulous','alarm elephant fabulous goat'}
k, v = string.match(a[1], 'alarm dentist (%w+) (%w+)')
print(k, v)
elephant fabulous
,而不是使用兩個變量,我想將其存儲在一個數組或表,但。我最終的目標是創建一個函數,在其中輸入一個數組(在這種情況下是'a')和一個模式(這種情況是'警報牙醫(%w +)(%w +)')和它返回所需的伴隨詞/ s,否則返回'nil'。問題在於模式查找的單詞數量未定義。在這種情況下是2,但我希望用戶能夠輸入任何模式,即'警報牙醫(%w +)(%w +)(%w +)(%w +)'或'警報牙醫(%w +)')。
所以這是我的思路到目前爲止:(我使用命令行工具在Ubuntu 12.04LTS進行測試)
a = {'alarm boy car dentist','alarm car dentist elephant','alarm dentist elephant fabulous','alarm elephant fabulous goat'}
function parse_strings (array, pattern)
words = nil
for i=1, #array do
c = string.match(array[i], pattern)
if c ~= nil then
words = c
end
end
return words
end
print (parse_strings (a, 'alarm dentist (%w+) (%w+)'))
elephant
但只有前值保存在「C」,而不是c [1] ='大象'和c [2] ='神話般'。
最壞的情況我可以搜索模式搜索的詞數,但我仍然需要找到一種方法將string.match
中未定義的大小輸出存儲在一個數組中。
爲什麼不使用'{string.match(whatever)}'而不是'table.pack(string.match(whatever))'? –
@NiccoloM。你是對的,我正在過度思考。我已經修改它使用表構造函數。謝謝。 –
非常感謝,工作。 – user3325563