Splitting a long string at every / in lua - lua

So I am making a function in lua where i wan't it to split a string at every "/" so for example:
local s = "Hello/GoodBye/Hi"
then i want it to split and input it to a table so it will look something like this:
Hello
GoodBye
Hi
This is my attempt but it doesn't really work:
local STR = "Hello/GoodBye/Hi"
strings = {}
for q,string in STR:gmatch("([/])(.-)%1") do
table.insert(strings, string)
end
That just returns:
Hello
Hi

That just returns:
Hello
Hi
When I run your code there is only a single element in strings which is "GoodBye".
The easiest way is to match anything that is not a / as in "[^/]+".
Also naming a variable string is not a good idea. You're shadowing Lua`s string library.

Related

Finding strings between two strings in lua

I have been trying to find all possible strings in between 2 strings
This is my input: "print/// to be able to put any amount of strings here endprint///"
The goal is to print every string in between print/// and endprint///
You can use Lua's string patterns to achieve that.
local text = "print/// to be able to put any amount of strings here endprint///"
print(text:match("print///(.*)endprint///"))
The pattern "print///(.*)endprint///" captures any character that is between "print///" and "endprint///"
Lua string patterns here
In this kind of problem, you don't use the greedy quantifiers * or +, instead, you use the lazy quantifier -. This is because * matches until the last occurrence of the sub-pattern after it, while - matches until the first occurence of the sub-pattern after it. So, you should use this pattern:
print///(.-)endprint///
And to match it in Lua, you do this:
local text = "print/// to be able to put any amount of strings here endprint///"
local match = text:match("print///(.-)endprint///")
-- `match` should now be the text in-between.
print(match) -- "to be able to put any amount of strings here "

can you use a colon in a key for a lua table

So I'm writing a program for the minecraft mod computercraft. I wanted to know if it was possible to do something like this:
tbl = {}
var = "minecraft:dirt"
tbl[var] = {pos ={0,0,0,1}}
For some reason I feel it doesnt save this table correctly so when I go to do
print(tbl["minecraft:dirt"].pos[4])
it errors
Can you use colons in keys?
tbl = {}
var = "minecraft:dirt"
tbl[var] = {pos ={0,0,0,1}}
print(tbl["minecraft:dirt"].pos[4])
prints 1
This is syntactically correct and should not result in any error message.
The only thing that won't work with colon is the syntactic sugar tbl.minecraft:dirt as Lua names may not contain colons. But if you use it like that tbl["minecraft:dirt"] colon is perfectly fine.
Long story short: Yes you can use colons in table keys.

How to print text form a particular part of a string?

I want to know how to get text form a particular part of a sentence this is what i mean. Hello (new text)., in the brackets it says new text and i want to find the text in the brackets and print only the text in the brackets.
With the ( and ) surrounding the text, you can use string.match:
str = "Hello (new text)"
print(str:match("%((.+)%)"))
%((.+)%)") is a pattern that captures every character between the ( and ).
Resources:
Lua 5.3 Reference Manual - 6.4.1 Patterns
The easiest way to do this is just to cancel out the Hello in your string.
local msg = "Hello (obama)"
msg = msg:gsub("Hello %(", ""):gsub("%)", "")
If the first part of the string is dynamic and is not always hello you can try this:
local msg = "Bye (obama)"
local pattern = "%p.+%p"
print(({string.match(msg, pattern):gsub("%)", ""):gsub("%(", "")})[1])
This soloution may not be the best and most efficient but it certainly works. I hope it helped you. Let me know if you have any questions.

How would I convert a string into a table?

I have been trying to convert a string into a table for example:
local stringtable = "{{"user123","Banned for cheating"},{"user124","Banned for making alt accounts"}}"
Code:
local table = "{{"user123","Banned for cheating"},{"user124","Banned for making alt accounts"}}"
print(table[1])
Output result:
Line 3: nil
Is there any sort of method of converting a string into a table? If so, let me know.
First of all, your Lua code will not work. You cannot have unescaped double quotes in a string delimited by double quotes. Use single quotes(') within a "-string, " within '...' or use heredoc syntax to be able to use both types of quotes, as shall I in the example below.
Secondly, your task cannot be solved with a regular expression, unless your table structure is very rigid; and even then Lua patterns will not be enough: you will need to use Perl-compatible regular expressions from Lua lrexlib library.
Thirdly, fortunately, Lua has a Lua interpreter available at runtime: the function loadstring. It returns a function that executes Lua code in its argument string. You just need to prepend return to your table code and call the returned function.
The code:
local stringtable = [===[
{{"user123","Banned for cheating"},{"user124","Banned for making alt accounts"}}
]===]
local tbl_func = loadstring ('return ' .. stringtable)
-- If stringtable is not valid Lua code, tbl_func will be nil:
local tbl = tbl_func and tbl_func() or nil
-- Test:
if tbl then
for _, user in ipairs (tbl) do
print (user[1] .. ': ' .. user[2])
end
else
print 'Could not compile stringtable'
end

string.format variable number of arguments

Luas string.format is pretty straight forward, if you know what to format.
However, I stuck at writing a function which takes a wildcard-string to format, and a variable number of arguments to put into that blank string.
Example:
str = " %5s %3s %6s %6s",
val = {"ttyS1", "232", "9600", "230400"}
Formatting that by hand is pretty easy:
string.format( str, val[1], val[2], val[3], val[4] )
Which is the same as:
string.format(" %5s %3s %6s %6s", "ttyS1, "232", "9600","230400")
But what if I wan't to have a fifth or sixth argument?
For example:
string.format(" %1s %2s %3s %4s %5s %6s %7s %", ... )
How can I implement a string.format with an variable number of arguments?
I want to avoid appending the values one by one because of performance issues.
The application runs on embedded MCUs.
Generate arbitrary number of repeats of whatever format you want with string.rep if format is the same for all arguments. Or fill table with all formats and use table.concat. Remember that you don't need to specify index of argument in format if you don't want to reorder them.
If you just need to concatenate strings together separated by space, use more suitable tool: table.concat(table_of_strings, ' ').
You can create a table using varargs:
function foo(fmt, ...)
local t = {...}
return t[6] -- might be nil
end
Ps, don't use # on the table if you expect the argument list might contain nil. Instead use select("#", ...).

Resources