[Home] [Downloads] [Search] [Help/forum]


Register forum user name Search FAQ

Gammon Forum

[Folder]  Entire forum
-> [Folder]  MUSHclient
. -> [Folder]  Lua
. . -> [Subject]  String Manipulation

String Manipulation

It is now over 60 days since the last post. This thread is closed.     [Refresh] Refresh page


Pages: 1  2 3  4  

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #15 on Sat 04 Feb 2012 02:48 PM (UTC)
Message
Nick Gammon said:

I don't understand what you are doing here, at all.

You shouldn't be storing your own variables in the global variable space. eg.


char = "Jim"

_G[char] = {}


Is basically:


 Jim = {}



True statement, that's exactly what I wanted it to be equivalent to. And I wasn't actually planning to put it in the global variable space when I used it, just done here as an example.

Nick Gammon said:

What if you have a character one day called "math" ? Then all your math functions go away.


I don't plan on naming my characters after any Lua libraries. :P

Nick Gammon said:

You should be storing game-related stuff in your own table, not _G.


I will be. The actual implementation will be something like this.


system[current_character] = "Jim"

system[system.current_character] = {} -- Creates a table that is the same as system.Jim

--Put GMCP data into the table I just created.

system[system.current_character] = {

	vitals = {

		hp	= t.hp,
		maxhp	= t.maxhp -- t is the table created from the rex.match function, hp and maxhp are named wildcards in the pattern.
	},
}

--Later I want to be able to do something like this to access the values of those stored variables, like this.

system[system.current_character]vitals.hp


See now?
[Go to top] top

Posted by Nick Gammon   Australia  (23,001 posts)  [Biography] bio   Forum Administrator
Date Reply #16 on Sun 05 Feb 2012 01:18 AM (UTC)
Message
Your idea of system [system.xxx] is very confusing. This code compiles at least, but I'm not sure it is the way to go:


t = {hp = 42, maxhp = 100}
system = { }

system.current_character = "Jim"

system [system.current_character] = {} -- Creates a table that is the same as system.Jim

--Put GMCP data into the table I just created.

system [system.current_character] = {

	vitals = {

		hp	= t.hp,
		maxhp	= t.maxhp -- t is the table created from the rex.match function, hp and maxhp are named wildcards in the pattern.
	},
}

--Later I want to be able to do something like this to access the values of those stored variables, like this.

print (system [system.current_character].vitals.hp )


- Nick Gammon

www.gammon.com.au, www.mushclient.com
[Go to top] top

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #17 on Sun 05 Feb 2012 11:10 PM (UTC)
Message
Well I did learn something important from testing in the Immediate script environment in MUSHclient

I was actually more worried about Lua having a syntax for -retrieving- a value specified by a variable more than setting it..which I already knew was possible. I just wasn't sure the specifics of how that worked.


char = "Jim"

system[char]  =  {
  vitals  =  {
    hp  =  300
  }
}

print (system[char].vitals.hp)

-->

300


char  =  "Jim"
test  =  "vitals"

system[char]  =  {
  [test]  =  {
    hp  =  300
  }
}

print (system[char].vitals.hp)
print (system[char][test].hp)

-->

300
300


They both work, but..


char = "Jim"

system[char]  =  {
  vitals  =  {
    hp  =  300
  }
}

print (system[char]vitals.hp)

-->

Compile Error


char  =  "Jim"
test  =  "vitals"

system[char]  =  {
  test  =  {
    hp  =  300
  }
}

print (system[char].test.hp)

-->

Compile Error


Does not work.

I did several other variations just to see what would work and what wouldn't. I'm just glad I got it sorted out before I coded the entire plugin and then realized it was one huge compile error.
[Go to top] top

Posted by Twisol   USA  (2,257 posts)  [Biography] bio
Date Reply #18 on Mon 06 Feb 2012 01:29 AM (UTC)
Message
Kevnuke said:

char  =  "Jim"
test  =  "vitals"

system[char]  =  {
  test  =  {
    hp  =  300
  }
}

print (system[char].test.hp)

-->

Compile Error

That one does work, actually; I just tried it. (Assuming a missing system = {}, anyways.)

You might be confused about how the table initializer syntax works. When you have {test=42}, it isn't using the value of the variable called 'test'; it's using the actual string value "test". In other words, {test=42} is a shorthand provided by Lua that's equivalent to {["test"]=42}. And in a similar vein, if you -do- want to use the value of a variable as the key, you can use {[test]=42}.

This also mimics the behavior of the table accessor syntax, where you have tbl.foo as a shorthand for tbl["foo"].

'Soludra' on Achaea

Blog: http://jonathan.com/
GitHub: http://github.com/Twisol
[Go to top] top

Posted by Nick Gammon   Australia  (23,001 posts)  [Biography] bio   Forum Administrator
Date Reply #19 on Mon 06 Feb 2012 03:16 AM (UTC)
Message
Yeah, I suggest you read the stuff about tables:

http://www.gammon.com.au/forum/?id=6036

Get comfortable with the simple stuff first. Naturally you can retrive things based on a variable.

But pay close attention to what Twisol said.

This syntax:

 
a = t [ bar ]


... indexes into table "t" by the contents of variable "bar", whatever that is.

However both of these do the same thing:

 
a = t [ "foo" ]
a = t.foo


They find the entry by the word "foo" - not some variable "foo".

- Nick Gammon

www.gammon.com.au, www.mushclient.com
[Go to top] top

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #20 on Mon 06 Feb 2012 10:44 PM (UTC)
Message
Twisol said:

Kevnuke said:

char  =  "Jim"
test  =  "vitals"

system[char]  =  {
  test  =  {
    hp  =  300
  }
}

print (system[char].test.hp)

-->

Compile Error

That one does work, actually; I just tried it. (Assuming a missing system = {}, anyways.)


Correct! Sorry, it was supposed to be
print (system[char].vitals.hp) demonstrating that unless you use the proper syntax it thinks you are literally making "test" the index, not the -contents- of a variable named "test", as you said.

Twisol said:

You might be confused about how the table initializer syntax works. When you have {test=42}, it isn't using the value of the variable called 'test'; it's using the actual string value "test". In other words, {test=42} is a shorthand provided by Lua that's equivalent to {["test"]=42}. And in a similar vein, if you -do- want to use the value of a variable as the key, you can use {[test]=42}.

This also mimics the behavior of the table accessor syntax, where you have tbl.foo as a shorthand for tbl["foo"].


Also correct! The point of all the experimenting I did was so that i wouldn't be confused about how the table initializer syntax worked anymore.

Thanks for all the help so far!
[Go to top] top

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #21 on Tue 07 Feb 2012 12:38 AM (UTC)

Amended on Tue 07 Feb 2012 12:53 AM (UTC) by Kevnuke

Message
Nick Gammon said:

Yeah, I suggest you read the stuff about tables:

http://www.gammon.com.au/forum/?id=6036

Get comfortable with the simple stuff first. Naturally you can retrive things based on a variable.


Thanks for the link, Nick. The part about using metatables to create defaults was really inspiring. It will likely save me a lot of time setting the same value for multiple sub-tables.

I guess I should just use the literal tables I'm going to be using. The two characters i have are Setru and Christopher on Achaea.

I wanted to create a separate sub-table within the table "system" for each character. BUT I was also going to put everything else in system = {} as well. For starters, just my balances (for use in my curing system). Eventually I wanted to do this..


a = some rex.new pattern with named wildcards that matches the Room.Info string

content = "the Room.Info string"

function RoomInfo (content)

_, _2, t = a:match(content)

if system.map[t.ID] then
  if content == system.map[t.ID].LAST_CONTENT then

    return

  else

    system.map = {

      [t.ID] = {

        roomName     = t.name,
        area         = t.area,
        environment  = t.environment,
        --etc
        LAST_CONTENT = content,

      },

    },

  end

else

  system.map = {

    [t.ID] = {

      roomName     = t.name,
      area         = t.area,
      environment  = t.environment,
      --etc
      LAST_CONTENT = content

    },

  },

  system[current_character].map = {

    [t.ID]         = system.map[t.ID]

  },

end --if

end --function


with the index of each entry in the system["map"] being the ID number of every room I've walked into. The first time I enter a room (ever, on any character) it is added to the system["map"] table as well as system[current_character].map (the map of the character I entered it with. This is so that later I have the option of comparing the system["map"] table with the map entries of the character I'm currently using to see if there are any I've missed. Whew!

OWWWW! My brain hurts now. I just did that code on the fly. Anything wrong with it?

EDIT: entered a few commas after table entries, just to be safe.
[Go to top] top

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #22 on Tue 07 Feb 2012 04:30 AM (UTC)

Amended on Tue 07 Feb 2012 05:04 AM (UTC) by Kevnuke

Message
I've also been wrestling with this one. This is the rex pattern I'm using to attempt to get exits and details from the string in content which is a sample GMCP Room.Info string.


ROOM_INFO  =  rex.new ('\{ \"num\"\: (?<ID>\d+)\, \"name\"\: \"(?<name>.+)\"\, \"area\"\: \"(?<area>.+)\"\, \"environment\"\: \"(?<environment>.+)\"\, \"coords\"\: \"[0-9\,]\"\, \"map\"\: \"\.+\"\, \"exits\"\: \{ (\"(?<exit>\w+)\"\: (?<exitID>\d+)[,]?[ ]?)* \}, \"details\"\: [ ("(?<detail>\w+)\"[,]?[ ]?])* ] }')

content  =  '{ "num": 12345, "name": "On a hill", "area": "Barren hills", "environment": "Hills", "coords": "45,5,4,3", "map": "www.imperian.com/itex/maps/clientmap.php?map=45&level=3 5 4", "exits": { "n": 12344, "se": 12336 }, "details": [ "shop", "bank" ] }'

function RoomInfo (content)

_, _2, t = ROOM_INFO:match(content)

if not system.map[t.exitID] then

	system.map[t.exitID] = {}

end

if system.map[t.ID] then

	if next (system.map[t.ID]) == nil then

		system.map[t.ID]	=	{

			name	=	t.name,
			area	=	t.area,
			--etc
			exits	=	{
				[t.exit]	=	system.map[t.exitID],
			},
			details	=	{
				t.details,
			},

		},

			LAST_ROOMINFO = content

	else

		if content == system.map[t.ID].LAST_ROOMINFO then

			return

		else

			system.map[t.ID]	=	{

				name	=	t.name,
				area	=	t.area,
				--etc
				exits	=	{
					[t.exit]	=	system.map[t.exitID],
				},
				details	=	{
					t.details,
				},

			},

			LAST_ROOMINFO = content

		end

	end

else

	system.map[t.ID]	=	{

		name	=	t.name,
		area	=	t.area,
		--etc
		exits	=	{
			[t.exit]	=	system.map[t.exitID],
		},
		details	=	{
			t.details,
		},

	},

		LAST_ROOMINFO = content

end

end


I -think- that code works. I'll check it while I'm offline. Also done on the fly, by the way.

EDIT: Quoted the string, I also forgot a space at the beginning of the object.
[Go to top] top

Posted by Twisol   USA  (2,257 posts)  [Biography] bio
Date Reply #23 on Tue 07 Feb 2012 04:55 AM (UTC)

Amended on Tue 07 Feb 2012 04:56 AM (UTC) by Twisol

Message
Whoa. Just run the GMCP payload through MUSHclient's bundled JSON library. A regexp is extremely brittle in this situation.

(Also, your code doesn't work. You dropped the GMCP payload directly into Lua without quoting it, and the JSON notation isn't syntactically compatible with Lua directly.)

local JSON = require "json"

content = [=[
{
  "num": 12345,
  "name": "On a hill",
  "area": "Barren hills",
  "environment": "Hills",
  "coords": "45,5,4,3",
  "map": "www.imperian.com/itex/maps/clientmap.php?map=45&level=3 5 4",
  "exits": { "n": 12344, "se": 12336 },
  "details": [ "shop", "bank" ]
}
]=]

tprint(JSON.decode("[" .. content .. "]")[0])


(The extra JSON array and subsequent index after decoding is to smooth out certain incompatibilies between JSON parsers. It doesn't matter for this particular payload, but for other GMCP messages it does matter. So I figured I'd play it safe and not assume anything about MUSHclient's JSON parser.)

'Soludra' on Achaea

Blog: http://jonathan.com/
GitHub: http://github.com/Twisol
[Go to top] top

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #24 on Tue 07 Feb 2012 05:09 AM (UTC)
Message
Umm..error


local JSON = require "json"
require "tprint"

content = [=[
{
  "num": 12345,
  "name": "On a hill",
  "area": "Barren hills",
  "environment": "Hills",
  "coords": "45,5,4,3",
  "map": "www.imperian.com/itex/maps/clientmap.php?map=45&level=3 5 4",
  "exits": { "n": 12344, "se": 12336 },
  "details": [ "shop", "bank" ]
}
]=]

tprint(JSON.decode("[" .. content .. "]")[0])

-->

Run-time error
World: Achaea
Immediate execution
C:\Games\MUSHclient\lua\tprint.lua:34: bad argument #1 to 'pairs' (table expected, got nil)
stack traceback:
        [C]: in function 'pairs'
        C:\Games\MUSHclient\lua\tprint.lua:34: in function 'tprint'
        [string "Immediate"]:16: in main chunk
[Go to top] top

Posted by Twisol   USA  (2,257 posts)  [Biography] bio
Date Reply #25 on Tue 07 Feb 2012 07:37 AM (UTC)

Amended on Tue 07 Feb 2012 07:38 AM (UTC) by Twisol

Message
Sorry, I'm used to working with 0-based arrays again.

local JSON = require "json"

content = [=[
{
  "num": 12345,
  "name": "On a hill",
  "area": "Barren hills",
  "environment": "Hills",
  "coords": "45,5,4,3",
  "map": "www.imperian.com/itex/maps/clientmap.php?map=45&level=3 5 4",
  "exits": { "n": 12344, "se": 12336 },
  "details": [ "shop", "bank" ]
}
]=]

tprint(JSON.decode("[" .. content .. "]")[1])

'Soludra' on Achaea

Blog: http://jonathan.com/
GitHub: http://github.com/Twisol
[Go to top] top

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #26 on Tue 07 Feb 2012 05:44 PM (UTC)
Message
Ohh just change the 0 to 1?
[Go to top] top

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #27 on Wed 08 Feb 2012 03:59 AM (UTC)
Message
So what does surrounding the GMCP data with [=[ ]=] do? I've never seen that used before.
[Go to top] top

Posted by Twisol   USA  (2,257 posts)  [Biography] bio
Date Reply #28 on Wed 08 Feb 2012 06:12 AM (UTC)
Message
Kevnuke said:
Ohh just change the 0 to 1?

Yep. Lua array indices start from 1, as opposed to indexing in languages like Java or C++, where indices start at 0.

Kevnuke said:
So what does surrounding the GMCP data with [=[ ]=] do? I've never seen that used before.

It's another way of making string literals, without dealing with escape characters. [[a"b'c]] is a string literal containing, a"b'c, and none of those quotes needed to be escaped. A possible issue is that the literal may contain ]] itself (just like you don't want " inside a "foo" literal), so Lua allows you to insert a number of ='s between the start and end brackets, as long as the number is the same.

'Soludra' on Achaea

Blog: http://jonathan.com/
GitHub: http://github.com/Twisol
[Go to top] top

Posted by Kevnuke   USA  (145 posts)  [Biography] bio
Date Reply #29 on Wed 08 Feb 2012 07:13 PM (UTC)
Message
Twisol said:

Kevnuke said:
So what does surrounding the GMCP data with [=[ ]=] do? I've never seen that used before.

It's another way of making string literals, without dealing with escape characters. [[a"b'c]] is a string literal containing, a"b'c, and none of those quotes needed to be escaped. A possible issue is that the literal may contain ]] itself (just like you don't want " inside a "foo" literal), so Lua allows you to insert a number of ='s between the start and end brackets, as long as the number is the same.

That's nifty! I was wondering what I'd do if there were single and double quotes in the same string.
[Go to top] top

The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).

To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.


99,681 views.

This is page 2, subject is 4 pages long:  [Previous page]  1  2 3  4  [Next page]

It is now over 60 days since the last post. This thread is closed.     [Refresh] Refresh page

Go to topic:           Search the forum


[Go to top] top

Quick links: MUSHclient. MUSHclient help. Forum shortcuts. Posting templates. Lua modules. Lua documentation.

Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.

[Home]


Written by Nick Gammon - 5K   profile for Nick Gammon on Stack Exchange, a network of free, community-driven Q&A sites   Marriage equality

Comments to: Gammon Software support
[RH click to get RSS URL] Forum RSS feed ( https://gammon.com.au/rss/forum.xml )

[Best viewed with any browser - 2K]    [Hosted at HostDash]