How to create a table of unique strings in Lua?

Viewed 331

I'm trying to create a function that adds unique string to a table. I also wonder how to print the result.

My Code :

local t = {}

function addUniqueString(str)
  --what should be here?
end

function printElements()
  --what should be here?
end

addUniqueString("apple")
addUniqueString("orange")
addUniqueString("banana")
addUniqueString("apple")
printElements()

The Result I want : (order doesn't matter)

apple
orange
banana
1 Answers

Since the order doesn't matter, you can just add strings as keys to the table:

local t = {}

function addUniqueString(str)
    t[str] = true
end

And to list the strings:

function printElements()
    for k in pairs(t) do
        print(k)
    end
end
Related