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.
How do i index strings and how it works?
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?"
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'
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'
https://www.lua.org/pil/2.5.html so, for example
local table = {} table['string index'] = 'hello, world!' print(table['string index']) --> hello, world!