Jump to content

HELP: Finding 'things inside strings'.


MTA.Castiel

Recommended Posts

Posted

Hello, im trying to output a 4 digit code from a random string but there is some error so i change > local theFoundCode = string.find(theCodeString, "%d%d%d%d") to local theFoundCode = string.find(theCodeString, "%d") and now it output "8". I'm trying to use string.find and seek "6970" inside of "abcdefg69hijklmn7opqrs0tuvw71xyz72", how to actually do this?

 

function seekCode(theSource)

	for index, player in ipairs (getElementsByType("player")) do

		local theCodeString = "abcdefg69hijklmn7opqrs0tuvw71xyz72"

		if theCodeString then
			local theFoundCode = string.find(theCodeString, "%d")
			outputChatBox( "The code is: " .. theCodeString .. " - FOUND: " .. theFoundCode, theSource)
			else
			outputChatBox( "n/a", theSource)
		end
	end
end
setTimer(seekCode, 1500, 0)

 

  • Moderators
Posted
20 minutes ago, MTA.Castiel said:

how to actually do this?

You can for example replace all non numeric characters with empty strings.

string.gsub("abcdefg69hijklmn7opqrs0tuvw71xyz72", "[^%d]", "") 
--[[
  Returns 2 values:
    Result: 69707172
    Items replaced (with empty string): 26
]]

 

 

  • Thanks 1

Do you want to improve your Lua programming skills and make less mistakes?   Start with Lua Language Server!   🙀

 

  Useful functions  3x 

  Tutorials  4x 

 

Posted

Well i can for example use:

string.gsub("abcdefg69hijklmn7opqrs0tuvw71xyz72", "[^%d]", "")

But that returns all the digits inside the string resulting in a value of "69707172". I'm only having difficulty getting the first 4 of them which in this "randomly generated string" is suppose to be "6970". Still clueless as to how it should be done IIYAMA

  • Moderators
Posted
7 hours ago, MTA.Castiel said:

I'm only having difficulty getting the first 4 of them

string.sub(string.gsub("abcdefg69hijklmn7opqrs0tuvw71xyz72", "[^%d]", ""), 1, 4) -- 6970

With string.sub you can make a selection of characters.

Arguments:

  1. The string
  2. Start index: 1
  3. End index: 4

https://www.tutorialspoint.com/string-sub-function-in-lua

  • Thanks 1

Do you want to improve your Lua programming skills and make less mistakes?   Start with Lua Language Server!   🙀

 

  Useful functions  3x 

  Tutorials  4x 

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...