2012-10-03 49 views
6

Necesito dividir una cadena y almacenarla en una matriz. Aquí utilicé el método string.gmatch, y está dividiendo los caracteres exactamente, pero mi problema es cómo almacenarlos en una matriz. aquí está mi guión mi muestra el formato de cadena: touchedSpriteName = Sprite, 10, subióDividir una cadena y almacenarla en una matriz en lua

objProp = {} 
for key, value in string.gmatch(touchedSpriteName,"%w+") do 
objProp[key] = value 
print (objProp[2]) 
end 

si i print (objProp) sus valores exactos que dan.

Respuesta

4

Su expresión devuelve solo un valor. Tus palabras terminarán en claves, y los valores permanecerán vacíos. Usted debe reescribir el bucle para iterar sobre un artículo, así:

objProp = { } 
touchedSpriteName = "touchedSpriteName = Sprite,10,rose" 
index = 1 

for value in string.gmatch(touchedSpriteName, "%w+") do 
    objProp[index] = value 
    index = index + 1 
end 

print(objProp[2]) 

Esto imprime Sprite (link de demostración en Ideone).

+0

hi dasblinkenlight, Gracias y ahora obtener la misma respuesta desde este enlace .. http://stackoverflow.com/questions/1426954/split-string-in-lua? rq = 1 – ssss05

4

Aquí hay una buena función que explota una cadena en una matriz. (Los argumentos son divider y string)

-- Source: http://lua-users.org/wiki/MakingLuaLikePhp 
-- Credit: http://richard.warburton.it/ 
function explode(div,str) 
    if (div=='') then return false end 
    local pos,arr = 0,{} 
    for st,sp in function() return string.find(str,div,pos,true) end do 
     table.insert(arr,string.sub(str,pos,st-1)) 
     pos = sp + 1 
    end 
    table.insert(arr,string.sub(str,pos)) 
    return arr 
end