Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Could I use table.insert to create a dictionary?

Asked by
Vrakos 109
10 years ago

If so, then how? I'm really stuck. :(

2 answers

Log in to vote
3
Answered by 10 years ago

Well, first you would need to create a table to collect all the words in. Next you would need a function to add words into it, you would probably create a table for two values, the word and the definition. Then create a function for finding definitions, so loop through the table checking the word and then return the definition when you find it. Something like this should suffice:

local Dictionary = {}

function AddWord(NewWord, NewDefenition)
    table.insert(Dictionary, {Word = NewWord, Defenition = NewDefenition})
end

function FindDefenition(TheWord)
    for i,v in next, Dictionary do
        if v.Word:lower() == TheWord:lower() then
            return v.Defenition
        end
    end
end

AddWord("ScriptingHelpers", "Organisation for helping people script")
local Defenition = FindDefenition("ScriptingHelpers")
print(Defenition) --Returns "Organisation for helping people script"
Ad
Log in to vote
1
Answered by
jobro13 980 Moderation Voter
10 years ago

Assuming that you mean with dictionary a table with non-numericial indices, such as:

local french_english = {
    pain = bread,
    amour = love
}
print("Translation of pain (french) to english: "..french_english["pain"])

Then you cannot use table.insert. Table.insert only works with numeric keys and will thus only work if you are creating a list.

However, what you need here is just the simple set operator for a table. Which is:

local tab = {}

tab.a = 3
tab["My Home"] = "United States"

print(tab.a) --> 3
print(tab["My Home"]) --> United States

You can use . for every key not starting with a number and not having spaces or other special characters in it.

To be safe, just use [] and put the key between those brackets.

Beware! tab.a = 3 sets tab["a"] to 3 tab[a] = 3 sets the CONTENT of a as key to tab.

Ex:

a = "my name"
tab[a] = "jobro"
tab.a = 3
print(tab.a, tab["my name"]) --> 3 jobro

Take a note of the fact that you can use anything as key in a table - except nil. Trying to set t[nil] will result in an error.

I hope this helped you a little bit in understanding tables with non-numerical keys (dictionaries).

Answer this question