lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


There is no [] acces for strings. You should use the sub function:

string.sub(a[1],1,1)
or
a[1]:sub(1,1)

If you need it, you can also implement the __index metamethod:

mt = getmetatable("")
mt.__index = function(s,i)
  return string.sub(s,i,i)
  end

--> a[1][1]

Alexandre

----- Reply message -----
From: meino.cramer@gmx.de
To: "Lua mailing list" <lua-l@lists.lua.org>
Subject: Accessing String contents
Date: Thu, Jun 21, 2012 05:37




Hi,

from a string in a table like this

    a={}
    a[1]="hello"

I want to access/retrieve the n-th character.

Somewhere I read about, that in lua everything is a table,
therefore I thought that

    =a[1][1]

would gives me "h" instead of an error.

But this may be thought too C-ish... ;)

I scanned through the String Tutorial, the String Library Tutotrial
and the online version of Programming Lua and found nothing what seems
appropiate to me...but I am sure that's due to me.... :)

What is the most cheapest (in terms of performance and programming
overhead) way to access the n-th character of a string which stored
at a certain index in a table?

Thank you very much in advance for any help!
Best regards,
mcc