WoW:USERAPI substr: Difference between revisions
Jump to navigation
Jump to search
m (New page: {{userfunc}} <!-- Leave this line in! --> <center>'''substr''' ''- by egingell -''</center> Imp strsub. Returns a string starting from ''start'' to ''leng...) |
mNo edit summary |
||
| Line 1: | Line 1: | ||
{{userfunc}} <!-- Leave this line in! --> | {{userfunc}} <!-- Leave this line in! --> | ||
Imp [[API_strsub|strsub]]. Returns a string starting from ''start'' to ''length'' characters from ''start'' (identical to the [http://php.net/substr PHP function] of the same name). | Imp [[API_strsub|strsub]]. Returns a string starting from ''start'' to ''length'' characters from ''start'' (identical to the [http://php.net/substr PHP function] of the same name). | ||
Revision as of 16:37, 4 December 2007
This page documents a user-defined function that you can copy and paste into your addon. Replace PREFIX with your addon or lib prefix to avoid conflicts between different versions of these functions.
Imp strsub. Returns a string starting from start to length characters from start (identical to the PHP function of the same name).
string = <PREFIX>_substr(string, start [, length])
Function Parameters
Arguments
- string
- String - The subject string.
- start
- Integer - Start here. 0 and 1 have the same effect. Negative values are acceptable.
- length
- Integer - Go this many characters and stop. Negative values are acceptable.
Returns
- string
- The desired piece of the string. If the resulting string is less than 0 characters long (which can only exist in the Twilight Zone), false is returned.
Examples
string = <PREFIX>_substr("World of Warcraft", 2, 4)
string = <PREFIX>_substr("World of Warcraft", -2, -4)
string = <PREFIX>_substr("World of Warcraft", -2, 4)
string = <PREFIX>_substr("World of Warcraft", -2, -1)
string = <PREFIX>_substr("World of Warcraft", 4, -1)
Results
"orld" false -- error condition: the resulting string is negative in length and, therefore, cannot exist. "ft" "f" "ld of Warcraf"
Code
function <PREFIX>_substr(string, start, length)
if not string then
return ''
end
-- Sanity checks: make sure integers are integers.
start = floor(tonumber(start)) or 1
if length == nil then
length = strlen(string)
end
if length < 0 and start < 0 and abs(length) > abs(start) then
return false
end
if start < 0 then
start = strlen(string) + (start + 1)
end
length = floor(tonumber(length))
local String = ''
if length >= 0 then
String = strsub(string, start, (start - 1) + length)
else
String = string
String = strsub(String, start)
String = strsub(String, 1, strlen(String) + length)
end
return String
end