Lua가 메모리 블록에서 임의의 바이트를 다른 유형과 바이트 순서로 읽고 쓸 수 있도록하는 라이브러리를 작성하고 있습니다. 어느 정도 반복을 피하기 위해 C ++ 템플릿을 사용했지만 완전히 피할 수는 없었습니다.
/* Read one or more sequential values from the blob and push to the Lua stack
* using lua_pushinteger().
* Lua: the Lua state to push to.
* offset: The byte offset to read from.
* count: The number of values to read.
* This method is called from Blob::read() which is called from Lua methods.
* For offsets outside the valid range, it returns nil.
*/
template <typename T>
lua_Integer Blob::readi(lua_State *Lua, lua_Integer offset, lua_Integer count) {
if(offset < 0) offset += this->size;
else offset--; //make 0-based
for(int i=0; i<count; i++) {
if(offset >= 0 && offset < this->size) {
T value = *(&this->data[offset + this->pageOffset]);
lua_pushinteger(Lua, value);
offset += sizeof(T);
}
else lua_pushnil(Lua);
}
return count;
}
/* Same as readi but uses lua_pushnumber
* even with templates we end up duplicating logic :|
*/
template <typename T>
lua_Integer Blob::readf(lua_State *Lua, lua_Integer offset, lua_Integer count) {
if(offset < 0) offset += this->size;
else offset--; //make 0-based
for(int i=0; i<count; i++) {
if(offset >= 0 && offset < this->size) {
T value = *(&this->data[offset + this->pageOffset]);
lua_pushnumber(Lua, value);
offset += sizeof(T);
}
else lua_pushnil(Lua);
}
return count;
}
float
또는 double
값 을 읽으려면 lua_pushnumber(lua_State *Lua, lua_Number num)
대신 을 사용해야 합니다 lua_pushinteger(lua_State *Lua, lua_Integer num)
. (일반적으로 lua_Integer
다음과 같은 몇 가지 중요한 유형의 형식 정의입니다 int32_t
, 그리고 lua_Number
의 형식 정의입니다 double
.) 나도 몰라 그래서 난 이후, 템플릿을 사용하여이 기능을 중복되지 않도록 할 수있는 방법 lua_pushinteger
과 lua_pushnumber
다른 유형에 동의합니다.
또한 바이트 순서 지정 (의 함수 사용)에 대한 지원을 추가하고 싶습니다 endian.h
. 읽는 값이 빅 엔디안 순서, 리틀 엔디안 또는 네이티브 (호스트 머신이 무엇이든간에)로 가정하도록 지정할 수 있습니다. 다시 말하지만, 바이트 순서 함수는 다른 유형을 다루기 때문에 템플릿으로이를 달성하는 방법을 모릅니다.
void lua_push_anything( lua_State* s, lua_Integer i ) {
lua_push_integer( s, i );
}
void lua_push_anything( lua_State* s, lua_Number i ) {
lua_push_number( s, i );
}
void lua_push_anything( lua_State* s, bool b ) {
lua_push_boolean( s, b ); // actually takes an `int`.
}
void lua_push_anything( lua_State* s, std::string s ) {
lua_pushlstring( lua_State* s, s.c_str(), s.size() );
}
이렇게하면 유형 문제가 해결 extern "C"
lua_*
됩니다. 올바른 함수로 전달되는 단일 재정의가 있습니다.
필요한 경우 비슷한 방식으로 엔디안을 처리 할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다