Modifying a character in a string in Lua

前端 未结 3 1677
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 23:17

Is there any way to replace a character at position N in a string in Lua.

This is what I\'ve come up with so far:

function replace_char(pos, str, r)
         


        
3条回答
  •  天命终不由人
    2021-01-02 23:38

    You should use pos inside your function instead of literal 1 and 3, but apart from this it looks good. Since Lua strings are immutable you can't really do much better than this.

    Maybe

     "%s%s%s":format(str:sub(1,pos-1), r, str:sub(pos+1, str:len())
    

    is more efficient than the .. operator, but I doubt it - if it turns out to be a bottleneck, measure it (and then decide to implement this replacement function in C).

提交回复
热议问题