This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
danieldigital's profile picture

Text adventure parsing help

Started by danieldigital, 07 May 2018 - 10:41 PM
danieldigital #1
Posted 08 May 2018 - 12:41 AM
Hey! This is my first post on the forum, and I'm not really that good at Lua either, so sorry if I miss something obvious.

[namedspoiler="really crappy explanation of what it should do]You still clicked show?
Fine, here's the explanation with my bad Lua knowledge.

So, I'm trying to seperate a string into a table.
The delimiter would be space, which means that it would seperate the words.
The last step is to reassemble all of the words in the table except the first one into a string.
Does that make any sense?
[/namedspoiler]
Ignore that ^^ it's probably not the best way

I'm trying to make a text adventure game and there will be one word commands.
However, there will be parameters after them.
So I need to seperate the first one and know what it is, but also know what all of the rest of them are together.

Just like I said at the top, if I'm missing something, tell me.
Saldor010 #2
Posted 08 May 2018 - 03:01 AM
Someone else will probably give a more detailed explanation later, but what you want to do can be achieved by using string.find along with string.sub (same website page). The basic idea of what you would do using string.find is this:

- Find the closest space in the string (using string.find)
- Remove everything from the start of the string to that point and store it in a table (using string.sub)
- Repeat first step with the new string until all spaces are gone

You should then have all of the words of your string separated into a table, from which you can do whatever you want with them.
Marc1miner #3
Posted 08 May 2018 - 03:09 AM
First of all you need to declare a table to store your words:

local words = { }
Then you should split the input string like this (assuming that it is user input, as you told)

string = read() 
for w in string:gmatch("%S+") do 
table.insert(words, w)        
end

The first line gets an user input, the for loop after that looks for white spaces between words and inserts them in a table.

To access those values or compare them to a set of commands do the following
Accessing: words[int] where int is the place of the word, starting at 1
Comparing: if words[int] == "moveUp" then (do some code)

I hope this clarifies a lot for you
danieldigital #4
Posted 09 May 2018 - 06:38 PM
Thanks so much for the help guys!
I will post a thread when it is done.