'Is there any way to find a string from a table?
I don't know if there's any way to find a string from a table in Lua that matches the argument for example.
function Library.Instance(object,name)
local Explorer = {}
local Storage = {
"fart",
}
if Storage == ((theobjectname)) then
print(object)
end
end
Solution 1:[1]
You have to implement it by yourself.
Here is my version of a tsearch()...
-- tsearch.lua
local magictab = {}
function magictab.tsearch(self, searchfor, replace)
local searchfor, replace, self = searchfor or 'Lua', replace or '<%1>', self or _G
for key, value in pairs(self) do
if type(value) == 'string' then
local found, count = value:gsub(searchfor, replace)
if count > 0 then
print('Key:', key, 'Found:', found)
end
end
end
end
-- Creating Key/Value Pairs
magictab['A Key With Spaces'] = 'Ghostbuster Goes Ghost Busting'
magictab[#magictab + 1] = 'Another Day - Another Table'
magictab[0] = 'Here I am - The Ghost Within Machine'
-- magictab.tsearch() -- Using defaults
return magictab
An impression typed in Lua Standalone...
$ /usr/local/bin/lua
Lua 5.4.3 Copyright (C) 1994-2021 Lua.org, PUC-Rio
> t=require('tsearch')
> t.tsearch()
Key: _VERSION Found: <Lua> 5.4
> t:tsearch('Ghost')
Key: A Key With Spaces Found: <Ghost>buster Goes <Ghost> Busting
Key: 0 Found: Here I am - The <Ghost> Within Machine
> t:tsearch('%u%l+','*%1*')
Key: 1 Found: *Another* *Day* - *Another* *Table*
Key: A Key With Spaces Found: *Ghostbuster* *Goes* *Ghost* *Busting*
Key: 0 Found: *Here* I am - *The* *Ghost* *Within* *Machine*
And...
This is only one way.
...there are many.
By the way...
Above tsearch() gives arguments 1:1 to gsub().
Therefore it could be a usefull training function for pattern matching and replacement checks.
For example: Do you know the pattern %f[] is usefull for?
Or: What is a replacement function?
> t:tsearch('%f[%u+%l+]',function(match_not_used_here) return '>>' end)
Key: 1 Found: >>Another >>Day - >>Another >>Table
Key: 0 Found: >>Here >>I >>am - >>The >>Ghost >>Within >>Machine
Key: A Key With Spaces Found: >>Ghostbuster >>Goes >>Ghost >>Busting
> t:tsearch('%f[^%u+%l+]',function(match_not_used_here) return '>>' end)
Key: 1 Found: Another>> Day>> - Another>> Table>>
Key: 0 Found: Here>> I>> am>> - The>> Ghost>> Within>> Machine>>
Key: A Key With Spaces Found: Ghostbuster>> Goes>> Ghost>> Busting>>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
