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
11 years ago

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

2 answers

Log in to vote
3
Answered by 11 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:

01local Dictionary = {}
02 
03function AddWord(NewWord, NewDefenition)
04    table.insert(Dictionary, {Word = NewWord, Defenition = NewDefenition})
05end
06 
07function FindDefenition(TheWord)
08    for i,v in next, Dictionary do
09        if v.Word:lower() == TheWord:lower() then
10            return v.Defenition
11        end
12    end
13end
14 
15AddWord("ScriptingHelpers", "Organisation for helping people script")
16local Defenition = FindDefenition("ScriptingHelpers")
17print(Defenition) --Returns "Organisation for helping people script"
Ad
Log in to vote
1
Answered by
jobro13 980 Moderation Voter
11 years ago

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

1local french_english = {
2    pain = bread,
3    amour = love
4}
5print("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:

1local tab = {}
2 
3tab.a = 3
4tab["My Home"] = "United States"
5 
6print(tab.a) --> 3
7print(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:

1a = "my name"
2tab[a] = "jobro"
3tab.a = 3
4print(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