Guest User

Untitled

a guest
Jul 30th, 2013
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.96 KB | None | 0 0
  1. -- Create table
  2. local items = {}
  3.  
  4. --Let's put stone ID at index "stone"
  5. items['stone'] = 1
  6.  
  7. --And torch at 50
  8. items['torch']= 50
  9.  
  10. -- Searching function
  11. local function search(table, toSearch)
  12.     -- Check if given table is actually table
  13.     if type(table) ~= "table" then
  14.         -- If it's not, raise error
  15.         error("Table expected, got "..type(table) or "nil", 2)
  16.     end
  17.    
  18.     -- Loop trough all values in given table
  19.     -- Set "index" to current item's index and set "value" to current item's value
  20.     for index, value in pairs(table) do
  21.         -- If we fount it
  22.         if index == toSearch then
  23.             -- Return fount value
  24.             return value
  25.         end
  26.     end
  27.    
  28.     -- If we reached this point it meas that items was not fount
  29.     -- Return false since nothing was fount
  30.     return false
  31. end
  32.  
  33. -- Some testing
  34.  
  35. -- Search for "stone" in table "items"
  36. print(tostring(search(items, "stone"))) --> 1
  37.  
  38. print(tostring(search(items, "noSuchThing"))) --> false
  39.  
  40. -- Search inside nil
  41. search(nil, "stone")
Advertisement
Add Comment
Please, Sign In to add comment