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

How do i index strings and how it works?

Asked by 5 years ago
Edited 5 years ago

Can someone pls explain to me how index strings works and how do i do it? Cause im really confused by some explanations and answers online.

Is it something like thing[stuff] = something ? and how it works?? need an explaination thanks.

All helps will be greatly appreciated. Will accept the most suitable answer.

2 answers

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

Question

How do i index strings and how it works?

My Answer

I can think of 2 cases what you mean by "index strings." The first case is "How do I index /set an index to a dictionary using a string?" The second case is *"How to directly index a string?"

Answer to first case

You can index a table with any datatype this includes strings, numbers, table, etc.

local dictionary = {
    ["apple"] = 123,
    [212] = "current rep"
}

print(dictionary["apple"]) --// gets index 'apple' then outputs its value '123'
print(dictionary[212]) --// gets index '212' then outputs its value 'current rep'

dictionary["epic"] = "sinistermemories" --// set to index to dictionary

print(dictionary["epic"]) --// outputs 'sinistermemories'

Answer to second case

Roblox has a sandboxed lua environment. If you are outside of that sandbox you can edit the global string metatable and you can allow strings to be indexed! It sounds crazy but lua has function for it.

local stringMeta = getmetatable("") --// get global string metatable
local stringMetaIndex = stringMeta.__index --// get `.__index` method of that metatable

function stringMeta.__index(self, x) --// define new index
    if not stringMetaIndex[x] then --// check if the index isn't in the original
        return self:sub(x, x) --// substring the string
    end

    return stringMetaIndex[x] --// return original index if condition pass failed
end


print(("hello")[1]) --// outputs 'h'
0
may i know whats golbal string metatable?? thanks Yokohane 50 — 5y
0
also dude can u explain to me how to use self:sub() and how it works?cause im really not that good in scripting, thanks Yokohane 50 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

https://www.lua.org/pil/2.5.html so, for example

local table = {}
table['string index'] = 'hello, world!'
print(table['string index']) --> hello, world!

Answer this question