tags:

views:

76

answers:

2

i am a new programmer and started with lua . i want to do the function that array a -b , the following are my program, it didn't work well

function delTwo (a ,b)  
local i = 0 
   local lengthA = #a
   local lengthB = #b


  for i = 1 ,lengthA do
   for j =1 , lengthB do
   if a[i]==b[j] then
   a[i] = nil
   end
  end

  for i = 1 , lengthA do
   if a[i]~= nil then
   retrun a[i]
   end
  end
  end

  end

a = {10, 20, 30} 
b={11,20,122}
for element in delTwo (a ,b)  do 
  print(element) 
end

I have two questions, the first is input:16: '=' expected near 'a' retrun a[i] Y should i changed into retrun =a[i] and what is the differences between them

the second is input:3: attempt to get length of local 'a' (a nil value) what is wrong with this, even if i changed into local lengthA = table.getn(a) there will be input:3: bad argument #1 to 'getn' (table expected, got nil)

+2  A: 

The first problem was already answered, but regarding the second it just means that a at some point of your program execution is nil (== null). I was not able to repeat this with your example though.

I am not completely certain what you are trying to achieve, but I recommend that you first create a function that creates a new table that stores the desired result and then iterate that using pairs (or normal looping). Something like the following:

function delTwo(a, b)
    local result = {}
    --# Logic here.
    --# Use result[#result + 1] = ... to insert values.
    return result
end

for k, v in pairs(delTwo(a,b)) do print(k, v) end
ponzao
i still have question with that, if i have a program like
workfor3days
function a (t) local i = 0 local n = table.getn(t) --local s =table.getn(s) return function () i = i + 1 if i <= n then return t[i] end -- for i= n+1, n+s do return s[i-n] end end end t = {10, 20, 30} for element in a(t) do print(element) end that will be correct
workfor3days
but if i change into function a (t, s) local i = 0 local n = table.getn(t) local s =table.getn(s) return function () i = i + 1 if i <= n then return t[i] end -- for i= n+1, n+s do return s[i-n] end end end t = {10, 20, 30} for element in a(t) do print(element) end it will be wrong Y function a (y,t) could not work?
workfor3days
@workfor3days Could you please insert the new code into your original question? It is really hard to follow the code when it is not formatted.
ponzao