Skip to content

Commit

Permalink
(#319) Impl utf8.len()
Browse files Browse the repository at this point in the history
  • Loading branch information
hymkor committed Aug 19, 2018
1 parent c209636 commit a300a61
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions mains/utf8lua.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package mains

import (
"strings"
"unicode/utf8"

"github.com/yuin/gopher-lua"
)
Expand Down Expand Up @@ -44,10 +45,62 @@ func utf8codes(L *lua.LState) int {
return 3
}

func utf8len(L *lua.LState) int {
_s, ok := L.Get(1).(lua.LString)
if !ok {
return lerror(L, "utf8.len(s,i,j): s is not string")
}
s := string(_s)
_len := len(s)

j := _len + 1
i := 1
top := L.GetTop()
if top >= 2 {
if _i, ok := L.Get(2).(lua.LNumber); ok {
i = int(_i)
} else {
return lerror(L, "utf8.len(s,i,j): i is not a number")
}
if top >= 3 {
if _j, ok := L.Get(3).(lua.LNumber); ok {
j = int(_j)
} else {
return lerror(L, "utf8.len(s,i,j): j is not a number)")
}
}
}
if j < 0 {
j += _len + 1
} else if j > 0 {
j--
}
if i < 0 {
i += _len + 1
} else if i > 0 {
i--
}
if !utf8.RuneStart(s[i]) {
return lerror(L, "utf8.len: not start byte")
}
s = s[i:]
j -= i
length := 0
for pos := range s {
if pos > j {
break
}
length++
}
L.Push(lua.LNumber(length))
return 1
}

func setupUtf8Table(L *lua.LState) {
table := L.NewTable()
L.SetField(table, "codes", L.NewFunction(utf8codes))
L.SetField(table, "charpattern", lua.LString("[\000-\x7F\xC2-\xF4][\x80-\xBF]*"))
L.SetField(table, "char", L.NewFunction(utf8char))
L.SetField(table, "len", L.NewFunction(utf8len))
L.SetGlobal("utf8", table)
}

0 comments on commit a300a61

Please sign in to comment.